normalize.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. import type {
  2. ChatAttachment,
  3. ChatMessage,
  4. CurrentUser,
  5. FileKind,
  6. FileLibraryItem,
  7. GroupAgent,
  8. GroupCapabilities,
  9. GroupInteraction,
  10. GroupMessage,
  11. GroupRoomDetail,
  12. GroupRoomActivity,
  13. GroupRoomSummary,
  14. GroupRun,
  15. GroupTopicSummary,
  16. JsonValue,
  17. ModelOption,
  18. Profile,
  19. SessionSummary,
  20. ToolCall,
  21. } from '@shared/types'
  22. export type UnknownRecord = Record<string, unknown>
  23. export function record(value: unknown): UnknownRecord {
  24. return value && typeof value === 'object' && !Array.isArray(value) ? value as UnknownRecord : {}
  25. }
  26. export function string(value: unknown, fallback = ''): string {
  27. if (typeof value === 'string') return value
  28. if (typeof value === 'number' && Number.isFinite(value)) return String(value)
  29. return fallback
  30. }
  31. export function number(value: unknown, fallback = 0): number {
  32. const parsed = typeof value === 'number' ? value : Number(value)
  33. return Number.isFinite(parsed) ? parsed : fallback
  34. }
  35. export function bool(value: unknown, fallback = false): boolean {
  36. if (typeof value === 'boolean') return value
  37. if (value === 1 || value === '1' || value === 'true') return true
  38. if (value === 0 || value === '0' || value === 'false') return false
  39. return fallback
  40. }
  41. export function values(value: unknown): unknown[] {
  42. return Array.isArray(value) ? value : []
  43. }
  44. function pick(source: UnknownRecord, ...keys: string[]): unknown {
  45. for (const key of keys) if (source[key] !== undefined && source[key] !== null) return source[key]
  46. return undefined
  47. }
  48. function jsonRecord(value: unknown): UnknownRecord {
  49. const direct = record(value)
  50. if (Object.keys(direct).length || typeof value !== 'string') return direct
  51. try { return record(JSON.parse(value)) } catch { return {} }
  52. }
  53. export function normalizeUser(value: unknown): CurrentUser {
  54. const source = record(value)
  55. const id = string(pick(source, 'id', 'user_id', 'userId')) || string(pick(source, 'email', 'username')) || 'local'
  56. return {
  57. id,
  58. username: string(pick(source, 'username', 'display_name', 'displayName', 'email', 'user_id', 'userId'), id),
  59. displayName: string(pick(source, 'display_name', 'displayName')) || undefined,
  60. email: string(source.email) || undefined,
  61. provider: string(source.provider) || undefined,
  62. role: string(source.role) || undefined,
  63. enabled: source.enabled === undefined ? undefined : bool(source.enabled),
  64. mustChangePassword: bool(pick(source, 'mustChangePassword', 'must_change_password')),
  65. }
  66. }
  67. export function normalizeProfile(value: unknown): Profile {
  68. const source = record(value)
  69. const name = string(pick(source, 'name', 'profile', 'id'), 'default')
  70. return {
  71. name,
  72. agentName: string(pick(source, 'agentName', 'agent_name')) || undefined,
  73. displayName: string(pick(source, 'display_name', 'displayName', 'alias', 'description')) || undefined,
  74. description: string(source.description) || undefined,
  75. isDefault: bool(pick(source, 'is_default', 'isDefault', 'active')),
  76. model: string(source.model) || undefined,
  77. provider: string(source.provider) || undefined,
  78. gatewayRunning: source.gateway_running === undefined && source.gatewayRunning === undefined
  79. ? undefined
  80. : bool(pick(source, 'gateway_running', 'gatewayRunning')),
  81. avatar: string(source.avatar) || undefined,
  82. agentAvatar: string(pick(source, 'agentAvatar', 'agent_avatar')) || undefined,
  83. }
  84. }
  85. export function normalizeModel(value: unknown): ModelOption {
  86. const source = record(value)
  87. const provider = string(source.provider)
  88. const id = string(pick(source, 'id', 'model', 'value'))
  89. return {
  90. id,
  91. name: string(pick(source, 'name', 'display_name', 'displayName'), id),
  92. provider,
  93. supportsReasoning: source.supports_reasoning === undefined && source.supportsReasoning === undefined
  94. ? undefined
  95. : bool(pick(source, 'supports_reasoning', 'supportsReasoning')),
  96. reasoningEfforts: values(pick(source, 'reasoning_efforts', 'reasoningEfforts')).map(value => string(value)).filter(Boolean),
  97. isDefault: bool(pick(source, 'is_default', 'isDefault')),
  98. }
  99. }
  100. export function normalizeSession(value: unknown, fallbackProfile?: string): SessionSummary {
  101. const source = record(value)
  102. const modelConfig = jsonRecord(pick(source, 'model_config', 'modelConfig'))
  103. const startedAt = number(pick(source, 'started_at', 'startedAt', 'created_at', 'createdAt'))
  104. const updatedAt = number(pick(source, 'last_active', 'lastActive', 'updated_at', 'updatedAt'), startedAt)
  105. const id = string(pick(source, 'id', 'session_id', 'sessionId', 'stored_session_id', 'storedSessionId'))
  106. return {
  107. id,
  108. profile: string(source.profile, fallbackProfile) || undefined,
  109. source: string(source.source, 'cli'),
  110. title: string(source.title, '未命名会话'),
  111. preview: string(source.preview) || undefined,
  112. model: string(source.model ?? modelConfig.model) || undefined,
  113. provider: string(source.provider ?? modelConfig.provider) || undefined,
  114. agent: string(source.agent) || undefined,
  115. messageCount: number(pick(source, 'message_count', 'messageCount')),
  116. toolCallCount: number(pick(source, 'tool_call_count', 'toolCallCount')),
  117. inputTokens: number(pick(source, 'input_tokens', 'inputTokens')) || undefined,
  118. outputTokens: number(pick(source, 'output_tokens', 'outputTokens')) || undefined,
  119. startedAt,
  120. updatedAt,
  121. endedAt: pick(source, 'ended_at', 'endedAt') == null ? null : number(pick(source, 'ended_at', 'endedAt')),
  122. parentSessionId: string(pick(source, 'parent_session_id', 'parentSessionId')) || null,
  123. forkPointMessageId: string(pick(source, 'fork_point_message_id', 'forkPointMessageId')) || null,
  124. workspace: string(source.workspace) || null,
  125. archived: bool(pick(source, 'is_archived', 'isArchived', 'archived')),
  126. pinned: bool(pick(source, 'is_pinned', 'isPinned', 'pinned')),
  127. }
  128. }
  129. function normalizeToolCall(value: unknown, index: number): ToolCall {
  130. const source = record(value)
  131. const functionCall = record(source.function)
  132. const error = string(source.error)
  133. const result = pick(source, 'result', 'output') as JsonValue | undefined
  134. return {
  135. id: string(pick(source, 'id', 'tool_call_id', 'toolCallId', 'tool_id'), `tool-${index}`),
  136. name: string(pick(source, 'name', 'tool_name', 'toolName') ?? functionCall.name, '工具'),
  137. status: error ? 'failed' : result !== undefined ? 'completed' : 'running',
  138. arguments: (pick(source, 'arguments', 'args', 'context') ?? functionCall.arguments) as JsonValue | undefined,
  139. result,
  140. preview: string(pick(source, 'preview', 'summary', 'args_text')) || undefined,
  141. error: error || undefined,
  142. durationSeconds: number(pick(source, 'duration_seconds', 'durationSeconds', 'duration_s')) || undefined,
  143. }
  144. }
  145. function parseJsonValue(value: unknown): JsonValue | undefined {
  146. if (typeof value !== 'string') return value as JsonValue | undefined
  147. try { return JSON.parse(value) as JsonValue } catch { return undefined }
  148. }
  149. export function normalizeAttachment(value: unknown, index = 0): ChatAttachment {
  150. const source = record(value)
  151. const mimeType = string(pick(source, 'mime_type', 'mimeType', 'media_type', 'mediaType'), 'application/octet-stream')
  152. const name = string(pick(source, 'name', 'filename'), `附件 ${index + 1}`)
  153. return {
  154. id: string(source.id, `${name}:${index}`),
  155. name,
  156. mimeType,
  157. size: number(source.size),
  158. path: string(source.path) || undefined,
  159. url: string(source.url) || undefined,
  160. kind: mimeType.startsWith('image/') ? 'image' : mimeType === 'application/pdf' ? 'pdf' : 'file',
  161. }
  162. }
  163. function attachmentMime(name: string): { mimeType: string; kind: ChatAttachment['kind'] } {
  164. const extension = name.split('.').at(-1)?.toLocaleLowerCase() || ''
  165. if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'heic', 'heif', 'avif', 'bmp', 'tif', 'tiff'].includes(extension)) {
  166. return { mimeType: `image/${extension === 'jpg' ? 'jpeg' : extension}`, kind: 'image' }
  167. }
  168. if (extension === 'pdf') return { mimeType: 'application/pdf', kind: 'pdf' }
  169. return { mimeType: 'application/octet-stream', kind: 'file' }
  170. }
  171. function persistedAttachmentUrl(path: string): { path: string; url: string } | undefined {
  172. if (path.startsWith('/')) return { path, url: path }
  173. const segments = path.split('/')
  174. const normalizedSegments = segments.map(segment => {
  175. try { return decodeURIComponent(segment) } catch { return '' }
  176. })
  177. if (segments[0] !== 'attachments' || segments.length < 2 || normalizedSegments.some(segment => !segment || segment === '.' || segment === '..')) return undefined
  178. return { path, url: `/${segments.map(encodeURIComponent).join('/')}` }
  179. }
  180. function persistedImageUrl(path: string): { path: string; url: string } | undefined {
  181. if (!path.startsWith('/')) return undefined
  182. const segments = path.slice(1).split('/')
  183. const normalizedSegments = segments.map(segment => {
  184. try { return decodeURIComponent(segment) } catch { return '' }
  185. })
  186. const rootImages = normalizedSegments[3] === 'images' && segments.length >= 5
  187. const profileImages = normalizedSegments[3] === 'profiles'
  188. && normalizedSegments[5] === 'images' && segments.length >= 7
  189. // User uploads belong to either the default Hermes home or the selected
  190. // Profile. Keep the full path so the Web media route reaches that Profile.
  191. if (normalizedSegments[0] !== 'Users' || normalizedSegments[2] !== '.hermes'
  192. || (!rootImages && !profileImages)
  193. || normalizedSegments.some(segment => !segment || segment === '.' || segment === '..' || /[/\\\u0000-\u001f\u007f]/.test(segment))) return undefined
  194. return { path, url: `/${segments.map(encodeURIComponent).join('/')}` }
  195. }
  196. function extractPersistedAttachments(content: string): { content: string; attachments: ChatAttachment[] } {
  197. const attachments: ChatAttachment[] = []
  198. const extracted = content.replace(
  199. /\[用户附加\s*(文件|图片|PDF)\s*:\s*([^\]\r\n]+)\]\s*(?:\r?\n)?@file:\s*(`[^`\r\n]+`|'[^'\r\n]+'|"[^"\r\n]+"|(?:\\?\/)[^\r\n]+)/g,
  200. (_match, _type: string, rawName: string, rawPath: string) => {
  201. const name = rawName.trim()
  202. const path = rawPath.trim().replace(/\\\//g, '/').replace(/^[`'"]|[`'"]$/g, '')
  203. const reference = persistedAttachmentUrl(path)
  204. if (!reference) return _match
  205. const media = attachmentMime(name)
  206. attachments.push({ id: `persisted:${reference.path}`, name, path: reference.path, url: reference.url, size: 0, ...media })
  207. return ''
  208. },
  209. )
  210. const cleaned = (attachments.length
  211. ? extracted.replace(/(?:^|\n)--- Attached Context ---[\s\S]*$/, '')
  212. : extracted
  213. ).replace(/\n{3,}/g, '\n\n').trim()
  214. return { content: cleaned, attachments }
  215. }
  216. function extractPersistedImages(content: string): { content: string; attachments: ChatAttachment[] } {
  217. const lines = content.split(/\r?\n/)
  218. const attachments: ChatAttachment[] = []
  219. const imageMarker = /^\[用户附加图片\s*:\s*([^\]\r\n]+)\]\s*$/
  220. const imageReference = /^@image:\s*(.+?)\s*$/
  221. const screenshot = /^\[screenshot\]\s*$/
  222. for (let index = 0; index < lines.length;) {
  223. const firstMarker = lines[index]?.match(imageMarker)
  224. if (!firstMarker) {
  225. index += 1
  226. continue
  227. }
  228. const start = index
  229. const names: string[] = []
  230. let cursor = index
  231. while (true) {
  232. const marker = lines[cursor]?.match(imageMarker)
  233. if (!marker) break
  234. names.push(marker[1]!.trim())
  235. cursor += 1
  236. while (lines[cursor]?.trim() === '') cursor += 1
  237. }
  238. const paths: string[] = []
  239. while (true) {
  240. const reference = lines[cursor]?.match(imageReference)
  241. if (!reference) break
  242. paths.push(reference[1]!.trim().replace(/^[`'"]|[`'"]$/g, ''))
  243. cursor += 1
  244. }
  245. const references = paths.map(persistedImageUrl)
  246. if (!paths.length || names.length !== paths.length || references.some(reference => !reference)) {
  247. index = start + 1
  248. continue
  249. }
  250. for (let position = 0; position < names.length; position += 1) {
  251. const reference = references[position]!
  252. const name = names[position]!
  253. attachments.push({ id: `persisted:${reference.path}`, name, path: reference.path, url: reference.url, size: 0, ...attachmentMime(name) })
  254. }
  255. while (screenshot.test(lines[cursor] || '')) cursor += 1
  256. lines.splice(start, cursor - start, ...Array(cursor - start).fill(''))
  257. index = cursor
  258. }
  259. return { content: lines.join('\n').replace(/\n{3,}/g, '\n\n').trim(), attachments }
  260. }
  261. export function normalizeChatMessage(value: unknown, sessionId: string, fallbackProfile?: string): ChatMessage {
  262. const source = record(value)
  263. const contentValue = pick(source, 'content', 'text', 'output')
  264. let content = typeof contentValue === 'string' ? contentValue : ''
  265. let attachments: ChatAttachment[] = values(pick(source, 'attachments', 'files')).map(normalizeAttachment)
  266. if (Array.isArray(contentValue)) {
  267. const textBlocks: string[] = []
  268. const attachmentBlocks: ChatAttachment[] = []
  269. contentValue.forEach((blockValue, index) => {
  270. const block = record(blockValue)
  271. const type = string(block.type)
  272. if (type === 'text') textBlocks.push(string(block.text))
  273. if (type === 'image' || type === 'file') attachmentBlocks.push(normalizeAttachment(block, index))
  274. })
  275. content = textBlocks.filter(Boolean).join('\n\n')
  276. attachments = [...attachments, ...attachmentBlocks]
  277. }
  278. const roleValue = string(source.role, 'assistant')
  279. const role = ['user', 'assistant', 'tool', 'system'].includes(roleValue) ? roleValue as ChatMessage['role'] : 'system'
  280. if (role === 'user' && (content.includes('@file:') || content.includes('@image:'))) {
  281. const persistedFiles = extractPersistedAttachments(content)
  282. const persistedImages = extractPersistedImages(persistedFiles.content)
  283. content = persistedImages.content
  284. const known = new Set(attachments.map(item => item.path || item.url || item.name))
  285. attachments.push(...[...persistedFiles.attachments, ...persistedImages.attachments]
  286. .filter(item => !known.has(item.path || item.url || item.name)))
  287. }
  288. const id = string(pick(source, 'id', 'message_id', 'messageId')) || `history-${sessionId}-${number(source.timestamp)}-${Math.random()}`
  289. const status = string(pick(source, 'status', 'finish_reason', 'finishReason'))
  290. return {
  291. id,
  292. serverMessageId: id,
  293. clientMessageId: string(pick(source, 'client_message_id', 'clientMessageId')) || undefined,
  294. sessionId,
  295. profile: string(source.profile, fallbackProfile) || undefined,
  296. role,
  297. content,
  298. reasoning: string(pick(source, 'reasoning', 'thinking', 'reasoning_content', 'reasoningContent')) || undefined,
  299. timestamp: number(pick(source, 'timestamp', 'created_at', 'createdAt', 'updated_at', 'updatedAt'), Date.now() / 1000),
  300. sequence: number(pick(source, 'seq', 'sequence')) || undefined,
  301. stage: status === 'error' || source.error ? 'failed' : 'settled',
  302. error: string(source.error) || undefined,
  303. attachments: attachments.length ? attachments : undefined,
  304. toolCalls: values(typeof pick(source, 'tool_calls', 'toolCalls', 'tools') === 'string'
  305. ? (() => { try { return JSON.parse(String(pick(source, 'tool_calls', 'toolCalls', 'tools'))) } catch { return [] } })()
  306. : pick(source, 'tool_calls', 'toolCalls', 'tools')).map(normalizeToolCall),
  307. toolCallId: string(pick(source, 'tool_call_id', 'toolCallId')) || undefined,
  308. toolName: string(pick(source, 'tool_name', 'toolName')) || undefined,
  309. displayKind: string(pick(source, 'display_kind', 'displayKind')) || undefined,
  310. displayMetadata: parseJsonValue(pick(source, 'display_metadata', 'displayMetadata')),
  311. raw: value as JsonValue,
  312. }
  313. }
  314. export function normalizeGroupCapabilities(value: unknown): GroupCapabilities {
  315. const source = record(value)
  316. const limits = record(source.limits)
  317. return {
  318. protocolVersion: number(pick(source, 'protocolVersion', 'protocol_version')),
  319. journalEpoch: string(pick(source, 'journalEpoch', 'journal_epoch')),
  320. latestCursor: number(pick(source, 'latestCursor', 'latest_cursor')),
  321. limits: {
  322. maxAgentsPerRoom: number(pick(limits, 'maxAgentsPerRoom', 'max_agents_per_room'), 8),
  323. maxMessageBytes: number(pick(limits, 'maxMessageBytes', 'max_message_bytes'), 64 * 1024),
  324. maxToolStateBytes: number(pick(limits, 'maxToolStateBytes', 'max_tool_state_bytes')) || undefined,
  325. maxInteractionPayloadBytes: number(pick(limits, 'maxInteractionPayloadBytes', 'max_interaction_payload_bytes')) || undefined,
  326. maxMessagePageSize: number(pick(limits, 'maxMessagePageSize', 'max_message_page_size'), 100),
  327. maxEventBatchSize: number(pick(limits, 'maxEventBatchSize', 'max_event_batch_size')) || undefined,
  328. maxAgentDepth: number(pick(limits, 'maxAgentDepth', 'max_agent_depth')) || undefined,
  329. maxRoomConcurrency: number(pick(limits, 'maxRoomConcurrency', 'max_room_concurrency')) || undefined,
  330. maxPluginConcurrency: number(pick(limits, 'maxPluginConcurrency', 'max_plugin_concurrency')) || undefined,
  331. defaultMaxReplyRounds: number(pick(limits, 'defaultMaxReplyRounds', 'default_max_reply_rounds'), 3),
  332. unlimitedReplyRoundsValue: number(pick(limits, 'unlimitedReplyRoundsValue', 'unlimited_reply_rounds_value'), -1),
  333. maxAgentDisplayNameLength: number(pick(limits, 'maxAgentDisplayNameLength', 'max_agent_display_name_length'), 100),
  334. },
  335. eventTypes: values(pick(source, 'eventTypes', 'event_types')).map(value => string(value)).filter(Boolean),
  336. features: values(source.features).map(value => string(value)).filter(Boolean),
  337. }
  338. }
  339. export function normalizeGroupAgent(value: unknown): GroupAgent {
  340. const source = record(value)
  341. const status = string(source.status, 'unknown') as GroupAgent['status']
  342. const rawFastMode = pick(source, 'fastMode', 'fast_mode')
  343. return {
  344. id: string(source.id), roomId: string(pick(source, 'roomId', 'room_id')),
  345. profile: string(source.profile),
  346. nodeId: string(pick(source, 'nodeId', 'node_id'), 'local'),
  347. nodeLabel: string(pick(source, 'nodeLabel', 'node_label')),
  348. displayName: string(pick(source, 'displayName', 'display_name'), string(source.profile)),
  349. description: string(source.description), storedSessionId: string(pick(source, 'storedSessionId', 'stored_session_id')) || null,
  350. lastContextMessageSeq: number(pick(source, 'lastContextMessageSeq', 'last_context_message_seq')),
  351. enabled: bool(source.enabled, true), replyWithoutMention: bool(pick(source, 'replyWithoutMention', 'reply_without_mention')),
  352. isHost: bool(pick(source, 'isHost', 'is_host')),
  353. model: string(source.model) || null, provider: string(source.provider) || null,
  354. reasoningEffort: string(pick(source, 'reasoningEffort', 'reasoning_effort')) || null,
  355. fastMode: rawFastMode == null ? null : bool(rawFastMode),
  356. createdAt: number(pick(source, 'createdAt', 'created_at')), updatedAt: number(pick(source, 'updatedAt', 'updated_at')),
  357. status: ['idle', 'queued', 'running', 'awaiting_input'].includes(status) ? status : 'unknown',
  358. }
  359. }
  360. export function normalizeGroupMessage(value: unknown): GroupMessage {
  361. const source = record(value)
  362. const senderKind = string(pick(source, 'senderKind', 'sender_kind'), 'unknown') as GroupMessage['senderKind']
  363. const status = string(source.status, 'unknown') as GroupMessage['status']
  364. return {
  365. seq: number(source.seq), id: string(source.id), roomId: string(pick(source, 'roomId', 'room_id')),
  366. topicId: string(pick(source, 'topicId', 'topic_id')) || null,
  367. senderKind: ['human', 'agent', 'system'].includes(senderKind) ? senderKind : 'unknown',
  368. senderId: string(pick(source, 'senderId', 'sender_id')), senderName: string(pick(source, 'senderName', 'sender_name')),
  369. rootMessageId: string(pick(source, 'rootMessageId', 'root_message_id')), replyToMessageId: string(pick(source, 'replyToMessageId', 'reply_to_message_id')) || null,
  370. clientMessageId: string(pick(source, 'clientMessageId', 'client_message_id')) || null,
  371. content: string(source.content), reasoning: string(source.reasoning), toolState: values(pick(source, 'toolState', 'tool_state')) as JsonValue[],
  372. status: ['queued', 'streaming', 'completed', 'failed', 'interrupted'].includes(status) ? status : 'unknown',
  373. error: string(source.error), execution: source.execution ? record(source.execution) as GroupMessage['execution'] : null, createdAt: number(pick(source, 'createdAt', 'created_at')), updatedAt: number(pick(source, 'updatedAt', 'updated_at')),
  374. }
  375. }
  376. export function normalizeGroupInteraction(value: unknown): GroupInteraction {
  377. const source = record(value)
  378. return {
  379. id: string(source.id), roomId: string(pick(source, 'roomId', 'room_id')), topicId: string(pick(source, 'topicId', 'topic_id')) || null,
  380. agentId: string(pick(source, 'agentId', 'agent_id')),
  381. runId: string(pick(source, 'runId', 'run_id')), kind: string(source.kind, 'unknown') as GroupInteraction['kind'],
  382. payload: (source.payload ?? null) as JsonValue, status: string(source.status, 'unknown') as GroupInteraction['status'],
  383. createdAt: number(pick(source, 'createdAt', 'created_at')), resolvedAt: pick(source, 'resolvedAt', 'resolved_at') == null ? null : number(pick(source, 'resolvedAt', 'resolved_at')),
  384. }
  385. }
  386. export function normalizeGroupRun(value: unknown): GroupRun {
  387. const source = record(value)
  388. const status = string(source.status, 'unknown') as GroupRun['status']
  389. const replyMode = string(pick(source, 'replyMode', 'reply_mode'))
  390. return {
  391. id: string(source.id), roomId: string(pick(source, 'roomId', 'room_id')),
  392. topicId: string(pick(source, 'topicId', 'topic_id')) || null,
  393. agentId: string(pick(source, 'agentId', 'agent_id')),
  394. triggerMessageId: string(pick(source, 'triggerMessageId', 'trigger_message_id')),
  395. responseMessageId: string(pick(source, 'responseMessageId', 'response_message_id')),
  396. rootMessageId: string(pick(source, 'rootMessageId', 'root_message_id')),
  397. depth: number(source.depth),
  398. status: ['queued', 'running', 'awaiting_input', 'completed', 'failed', 'interrupted'].includes(status) ? status : 'unknown',
  399. runtimeSessionId: string(pick(source, 'runtimeSessionId', 'runtime_session_id')) || null,
  400. error: string(source.error),
  401. replyMode: replyMode === 'mentioned' || replyMode === 'automatic' ? replyMode : null,
  402. createdAt: number(pick(source, 'createdAt', 'created_at')),
  403. updatedAt: number(pick(source, 'updatedAt', 'updated_at')),
  404. }
  405. }
  406. export function normalizeGroupTopic(value: unknown): GroupTopicSummary {
  407. const source = record(value)
  408. return {
  409. id: string(source.id), roomId: string(pick(source, 'roomId', 'room_id')),
  410. title: string(source.title, '新话题'), preview: string(source.preview),
  411. messageCount: number(pick(source, 'messageCount', 'message_count')),
  412. unreadCount: number(pick(source, 'unreadCount', 'unread_count')),
  413. latestMessageSeq: number(pick(source, 'latestMessageSeq', 'latest_message_seq')),
  414. createdAt: number(pick(source, 'createdAt', 'created_at')),
  415. updatedAt: number(pick(source, 'updatedAt', 'updated_at')),
  416. archived: bool(source.archived),
  417. pinned: bool(source.pinned),
  418. }
  419. }
  420. export function normalizeGroupRoom(value: unknown): GroupRoomSummary {
  421. const source = record(value)
  422. const rawAgents = source.agents
  423. const orchestrationMode = string(pick(source, 'orchestrationMode', 'orchestration_mode'))
  424. return {
  425. id: string(source.id), name: string(source.name, '未命名团队'), cwd: string(source.cwd), instructions: string(source.instructions), avatar: string(source.avatar),
  426. avatarMembers: values(pick(source, 'avatarMembers', 'avatar_members')).flatMap(value => {
  427. const member = record(value)
  428. const profile = string(member.profile)
  429. if (!profile) return []
  430. return [{ profile, nodeId: string(pick(member, 'nodeId', 'node_id'), 'local'), displayName: string(pick(member, 'displayName', 'display_name'), profile) }]
  431. }),
  432. createdAt: number(pick(source, 'createdAt', 'created_at')), updatedAt: number(pick(source, 'updatedAt', 'updated_at')),
  433. archived: bool(source.archived), agentCount: Array.isArray(rawAgents) ? rawAgents.length : number(pick(source, 'agentCount', 'agent_count')),
  434. lastMessage: source.lastMessage || source.last_message ? normalizeGroupMessage(pick(source, 'lastMessage', 'last_message')) : null,
  435. unreadCount: number(pick(source, 'unreadCount', 'unread_count')),
  436. activeRunCount: number(pick(source, 'activeRunCount', 'active_run_count')),
  437. maxReplyRounds: number(pick(source, 'maxReplyRounds', 'max_reply_rounds'), 3),
  438. orchestrationMode: orchestrationMode === 'host' ? 'host' : 'free',
  439. }
  440. }
  441. export function normalizeGroupRoomActivity(value: unknown): GroupRoomActivity {
  442. const source = record(value)
  443. const lastMessage = pick(source, 'lastMessage', 'last_message')
  444. return {
  445. roomId: string(pick(source, 'roomId', 'room_id')),
  446. activeRunCount: number(pick(source, 'activeRunCount', 'active_run_count')),
  447. unreadCount: number(pick(source, 'unreadCount', 'unread_count')),
  448. lastMessage: lastMessage == null ? null : normalizeGroupMessage(lastMessage),
  449. }
  450. }
  451. export function normalizeGroupRoomDetail(value: unknown): GroupRoomDetail {
  452. const source = record(value)
  453. const summary = normalizeGroupRoom(source)
  454. return {
  455. id: summary.id, name: summary.name, cwd: summary.cwd, instructions: summary.instructions, avatar: summary.avatar, avatarMembers: summary.avatarMembers, createdAt: summary.createdAt, updatedAt: summary.updatedAt,
  456. archived: summary.archived, maxReplyRounds: summary.maxReplyRounds, orchestrationMode: summary.orchestrationMode,
  457. agents: values(source.agents).map(normalizeGroupAgent), runs: values(source.runs).map(normalizeGroupRun),
  458. pendingInteractions: values(pick(source, 'pendingInteractions', 'pending_interactions')).map(normalizeGroupInteraction),
  459. latestCursor: number(pick(source, 'latestCursor', 'latest_cursor')),
  460. }
  461. }
  462. export function inferFileKind(mimeType: string, name: string): FileKind {
  463. const mime = mimeType.toLowerCase().split(';')[0]
  464. if (mime.startsWith('image/')) return 'image'
  465. if (mime.startsWith('video/')) return 'video'
  466. if (mime.startsWith('audio/')) return 'audio'
  467. if (mime.startsWith('text/') || /\.(pdf|docx?|xlsx?|pptx?|md|txt|csv|json|rtf|pages|numbers|key)$/i.test(name)) return 'document'
  468. return 'other'
  469. }
  470. export function normalizeFile(value: unknown, fallbackProfile?: string): FileLibraryItem {
  471. const source = record(value)
  472. const id = string(pick(source, 'id', 'fileId', 'file_id'))
  473. const mimeType = string(pick(source, 'mimeType', 'mime_type'), 'application/octet-stream')
  474. const name = string(source.name)
  475. const origins = values(source.origins).map(item => {
  476. const origin = record(item)
  477. return {
  478. id: origin.id as number | string | undefined,
  479. profile: string(origin.profile) || fallbackProfile || undefined,
  480. sessionId: string(pick(origin, 'sessionId', 'session_id')) || undefined,
  481. workspaceConversationId: string(origin.workspaceConversationId) || undefined,
  482. sessionTitle: string(pick(origin, 'sessionTitle', 'session_title')) || undefined,
  483. messageId: string(pick(origin, 'messageId', 'message_id')) || undefined,
  484. authorKind: string(pick(origin, 'authorKind', 'author_kind')) as FileLibraryItem['origins'][number]['authorKind'] || undefined,
  485. authorName: string(pick(origin, 'authorName', 'author_name')) || undefined,
  486. observedAt: number(pick(origin, 'observedAt', 'observed_at')) || undefined,
  487. originalPath: string(pick(origin, 'originalPath', 'original_path')) || undefined,
  488. referencePath: string(pick(origin, 'referencePath', 'reference_path')) || undefined,
  489. }
  490. })
  491. const profile = origins.find(origin => origin.profile)?.profile
  492. const profileQuery = profile ? `?profile=${encodeURIComponent(profile)}` : ''
  493. return {
  494. id, path: string(source.path), name, extension: string(pick(source, 'extension', 'extensionName', 'extension_name')),
  495. mimeType, size: number(source.size), modifiedAt: number(pick(source, 'modifiedAt', 'modified_at')),
  496. exists: bool(source.exists, true), availability: string(source.availability) as FileLibraryItem['availability'] || undefined,
  497. archiveStatus: string(pick(source, 'archiveStatus', 'archive_status')) || undefined,
  498. firstSeenAt: number(pick(source, 'firstSeenAt', 'first_seen_at')) || undefined,
  499. lastSeenAt: number(pick(source, 'lastSeenAt', 'last_seen_at')) || undefined,
  500. messageTimestamp: pick(source, 'messageTimestamp', 'message_timestamp') == null ? null : number(pick(source, 'messageTimestamp', 'message_timestamp')),
  501. origins, kind: inferFileKind(mimeType, name),
  502. previewUrl: string(pick(source, 'previewUrl', 'preview_url'))
  503. || `/api/app/files/${encodeURIComponent(id)}/preview${profileQuery}`,
  504. downloadUrl: string(pick(source, 'downloadUrl', 'download_url'))
  505. || `/api/app/files/${encodeURIComponent(id)}/download${profileQuery}`,
  506. }
  507. }