util.ts 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import MarkdownIt from 'markdown-it'
  2. export function formatSize(n: number) {
  3. if (n < 1024) return `${n} B`
  4. if (n < 1048576) return `${(n / 1024).toFixed(1)} KB`
  5. return `${(n / 1048576).toFixed(1)} MB`
  6. }
  7. export function basename(p: string) {
  8. return p.split('/').pop() ?? p
  9. }
  10. const TOOL_LABELS: Record<string, string> = {
  11. 'mcp__gateway__convert_document': 'Convert',
  12. 'mcp__gateway__recalc_workbook': 'Recalc',
  13. 'mcp__gateway__web_fetch': 'Fetch',
  14. 'mcp__gateway__kb_list_roots': 'Knowledge',
  15. 'AskUserQuestion': 'Question',
  16. 'WebFetch': 'Fetch',
  17. 'WebSearch': 'Search',
  18. 'TodoWrite': 'Todo',
  19. }
  20. export function toolLabel(name: string) {
  21. if (TOOL_LABELS[name]) return TOOL_LABELS[name]
  22. if (name.startsWith('mcp__')) return name.split('__').slice(2).join('.')
  23. return name
  24. }
  25. export function fileIcon(mime: string, path: string) {
  26. const ext = path.split('.').pop()?.toLowerCase() ?? ''
  27. if (mime.startsWith('image/')) return 'codicon-file-media'
  28. if (['xlsx', 'xls', 'csv', 'ods'].includes(ext)) return 'codicon-table'
  29. if (ext === 'pdf') return 'codicon-file-pdf'
  30. if (['docx', 'doc', 'md', 'txt', 'odt'].includes(ext)) return 'codicon-file-text'
  31. if (['zip', 'tar', 'gz'].includes(ext)) return 'codicon-file-zip'
  32. if (['py', 'js', 'ts', 'json', 'html', 'sql', 'sh'].includes(ext)) return 'codicon-file-code'
  33. return 'codicon-file'
  34. }
  35. const md = new MarkdownIt({ html: false, linkify: true, breaks: false, typographer: false })
  36. const defaultLink = md.renderer.rules.link_open ?? ((tokens, idx, options, _env, self) => self.renderToken(tokens, idx, options))
  37. md.renderer.rules.link_open = (tokens, idx, options, env, self) => {
  38. tokens[idx]!.attrSet('target', '_blank')
  39. tokens[idx]!.attrSet('rel', 'noopener noreferrer')
  40. return defaultLink(tokens, idx, options, env, self)
  41. }
  42. export function renderMarkdown(src: string) {
  43. return md.render(src)
  44. }
  45. export function stringifyInput(input: unknown) {
  46. if (input === null || input === undefined) return ''
  47. if (typeof input === 'string') return input
  48. try {
  49. return JSON.stringify(input, null, 2)
  50. } catch {
  51. return String(input)
  52. }
  53. }