normalize.ts 27 KB

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