normalize.ts 25 KB

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