Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript
11.9 KB
Raw Blame
import type { ChatMessageAttachment } from '../../../src/types'
import type {
  ComposerImageAttachment,
  ComposerReferenceAttachment,
  ReadyComposerFileAttachment,
} from '../uiTypes'

type ParsedChatMessageDisplay = {
  content: string
  attachments: ChatMessageAttachment[]
}

function attachmentOrder(value: { addedOrder?: number }, fallbackIndex: number): number {
  return value.addedOrder ?? fallbackIndex
}

function formatUploadedFileTooltip(attachment: { sizeBytes: number }): string {
  return `Uploaded File - ${Math.max(1, Math.round(attachment.sizeBytes / 1024))} KB`
}

function normalizeAttachmentLabel(label: string): string {
  return label.replace(/\s+/g, ' ').trim()
}

function formatParsedAttachmentLabel(type: ChatMessageAttachment['type'], label: string): string {
  const normalizedLabel = normalizeAttachmentLabel(label)
  if (type === 'global_file') {
    const labeledReference = normalizedLabel.match(/^(.*?)\s+\(gfs:\/\/[^)]+\)$/i)
    if (labeledReference?.[1]?.trim()) return labeledReference[1].trim()
    const normalizedPath = normalizedLabel.replace(/^gfs:\/\/[^/]+\//i, '').replace(/\/+$/g, '')
    const basename = normalizedPath.split('/').filter(Boolean).pop()
    if (!basename) return normalizedLabel
    try {
      return decodeURIComponent(basename)
    } catch {
      return basename
    }
  }
  if (type !== 'agent_file') return normalizedLabel
  const normalizedPath = normalizedLabel.replace(/^\/+|\/+$/g, '')
  return normalizedPath.split('/').filter(Boolean).pop() || normalizedLabel
}

const PROMPT_LISTS: { prefix: string; type: ChatMessageAttachment['type'] }[] = [
  { prefix: 'Plugins:', type: 'plugin' },
  { prefix: 'Connectors:', type: 'connector' },
  { prefix: 'Agent Files:', type: 'agent_file' },
  { prefix: 'Global Files:', type: 'global_file' },
]

function createParsedAttachment(
  type: ChatMessageAttachment['type'],
  label: string,
  index: number,
  quoted = false
): ChatMessageAttachment | null {
  // A quoted Global Files entry is the file's label, never a gfs:// URI.
  const normalizedLabel =
    quoted && type === 'global_file'
      ? normalizeAttachmentLabel(label)
      : formatParsedAttachmentLabel(type, label)
  if (!normalizedLabel) return null
  return {
    id: `parsed:${type}:${index}:${normalizedLabel}`,
    type,
    label: normalizedLabel,
    addedOrder: index,
    ...(type === 'agent_file' ? parseAgentFileIdentity(label) : {}),
    ...(type === 'global_file' ? parseGlobalFileIdentity(label) : {}),
  }
}

function parseAgentFileIdentity(
  value: string
): Pick<ChatMessageAttachment, 'filesystemName' | 'path'> {
  const slash = value.indexOf('/')
  return slash > 0 && slash < value.length - 1
    ? { filesystemName: value.slice(0, slash), path: value.slice(slash + 1) }
    : {}
}

function parseGlobalFileIdentity(
  value: string
): Pick<ChatMessageAttachment, 'drive' | 'resourceId' | 'gfsUri'> {
  const gfsUri = value.match(/(?:^|\()(gfs:\/\/[^)\s]+)\)?$/i)?.[1]
  const uriParts = gfsUri?.match(/^gfs:\/\/([^/]+)\/(.+)$/i)
  return gfsUri && uriParts?.[1] && uriParts[2]
    ? { gfsUri, drive: uriParts[1], resourceId: uriParts[2] }
    : {}
}

function inferLegacyContextAttachmentType(label: string): ChatMessageAttachment['type'] {
  const normalizedLabel = label.trim().toLowerCase()
  if (normalizedLabel.startsWith('mcp-') || normalizedLabel.endsWith('-remote')) {
    return 'connector'
  }
  if (normalizedLabel.includes('/') || /\.[a-z0-9]{2,6}$/i.test(normalizedLabel)) {
    return 'agent_file'
  }
  return 'plugin'
}

type ParsedAttachmentList = { labels: string[]; quoted: boolean }

/**
 * Reads the list the composer wrote as JSON string literals:
 * `"a", "b". <instruction>`. A list that does not parse as that form yields no
 * entries, because its boundaries cannot be known. `null` marks the one case
 * that is provably a pre-#666 list: a label parsed cleanly, then a dot glued
 * to more list text instead of the sentence's instruction.
 */
function parseQuotedAttachmentList(value: string): string[] | null {
  const labels: string[] = []
  let index = 0
  while (index < value.length && value[index] === '"') {
    let end = index + 1
    while (end < value.length && value[end] !== '"') end += value[end] === '\\' ? 2 : 1
    if (end >= value.length) return []
    let label: unknown
    try {
      label = JSON.parse(value.slice(index, end + 1))
    } catch {
      return []
    }
    if (typeof label !== 'string') return []
    labels.push(label)
    index = end + 1
    if (value.startsWith(', ', index)) {
      index += 2
      continue
    }
    if (index >= value.length) return labels
    if (value[index] !== '.') return []
    const rest = value.slice(index + 1)
    return rest === '' || rest.startsWith(' ') ? labels : null
  }
  return []
}

/** Messages sent before #666 wrote the list unquoted; they are read as before. */
function parseAttachmentList(value: string): ParsedAttachmentList {
  const trimmed = value.trimStart()
  if (trimmed.startsWith('"')) {
    const labels = parseQuotedAttachmentList(trimmed)
    if (labels !== null) return { labels, quoted: true }
  }
  const itemList = trimmed.split(/\.\s+/)[0] ?? ''
  return {
    labels: itemList
      .split(',')
      .map(item => item.trim())
      .filter(Boolean),
    quoted: false,
  }
}

export function buildChatMessageAttachments(
  imageAttachments: ComposerImageAttachment[],
  referenceAttachments: ComposerReferenceAttachment[],
  fileAttachments: ReadyComposerFileAttachment[]
): ChatMessageAttachment[] {
  const referenceItems = referenceAttachments.map((attachment, index): ChatMessageAttachment => {
    const type = attachment.type
    return {
      id: attachment.id,
      type,
      label: attachment.label,
      tooltip:
        attachment.type === 'plugin'
          ? 'Plugin'
          : attachment.type === 'connector'
            ? 'Connector'
            : attachment.type === 'global_file'
              ? 'Global File'
              : 'Agent File',
      addedOrder: attachmentOrder(attachment, index),
      ...(attachment.type === 'agent_file'
        ? { filesystemName: attachment.filesystemName, path: attachment.path }
        : {}),
      ...(attachment.type === 'global_file'
        ? {
            gfsUri: attachment.gfsUri,
            drive: attachment.drive,
            resourceId: attachment.resourceId,
            version: attachment.version,
            bytes: attachment.bytes,
          }
        : {}),
    }
  })
  const imageItems = imageAttachments.map((attachment, index): ChatMessageAttachment => {
    const fallbackIndex = referenceItems.length + index
    return {
      id: attachment.id,
      type: 'uploaded_file',
      label: attachment.name,
      tooltip: formatUploadedFileTooltip(attachment),
      addedOrder: attachmentOrder(attachment, fallbackIndex),
      // BUG-176: keep the image bytes on the display attachment so the
      // sent-message chip can reopen the shared image preview. Persisted with
      // the user message (same inline-base64 contract as response_file).
      filename: attachment.name,
      mimeType: attachment.mimeType,
      encoding: 'base64',
      dataBase64: attachment.dataBase64,
      sizeBytes: attachment.sizeBytes,
    }
  })
  const fileItems = fileAttachments.map((attachment, index): ChatMessageAttachment => {
    const fallbackIndex = referenceItems.length + imageItems.length + index
    return {
      id: attachment.id,
      type: 'uploaded_file',
      label: attachment.filename,
      tooltip: formatUploadedFileTooltip(attachment),
      addedOrder: attachmentOrder(attachment, fallbackIndex),
    }
  })
  return [...referenceItems, ...imageItems, ...fileItems].sort(
    (a, b) => attachmentOrder(a, 0) - attachmentOrder(b, 0)
  )
}

export function getChatMessageAttachmentTypeLabel(type: ChatMessageAttachment['type']): string {
  if (type === 'plugin') return 'Plugin'
  if (type === 'connector') return 'Connector'
  if (type === 'agent_file') return 'Agent File'
  if (type === 'global_file') return 'Global File'
  if (type === 'response_file') return 'Generated File'
  return 'Uploaded File'
}

export function buildResponseFileAttachments(response: unknown): ChatMessageAttachment[] {
  const record =
    response && typeof response === 'object' && !Array.isArray(response)
      ? (response as Record<string, unknown>)
      : {}
  const rawAttachments = Array.isArray(record.attachments) ? record.attachments : []
  return rawAttachments
    .map((raw, index): ChatMessageAttachment | null => {
      const attachment =
        raw && typeof raw === 'object' && !Array.isArray(raw)
          ? (raw as Record<string, unknown>)
          : null
      if (!attachment) return null
      if (attachment.kind !== 'file') return null
      if (attachment.encoding !== 'base64') return null
      const filename =
        typeof attachment.filename === 'string' && attachment.filename.trim()
          ? attachment.filename.trim()
          : ''
      const dataBase64 =
        typeof attachment.dataBase64 === 'string' && attachment.dataBase64
          ? attachment.dataBase64
          : ''
      if (!filename || !dataBase64) return null
      const mimeType =
        typeof attachment.mimeType === 'string' && attachment.mimeType.trim()
          ? attachment.mimeType.trim()
          : 'application/octet-stream'
      const sizeBytes =
        typeof attachment.sizeBytes === 'number' && Number.isFinite(attachment.sizeBytes)
          ? attachment.sizeBytes
          : undefined
      return {
        id:
          typeof attachment.id === 'string' && attachment.id.trim()
            ? attachment.id.trim()
            : `response-file:${index}:${filename}`,
        type: 'response_file',
        label: filename,
        tooltip: sizeBytes
          ? `Generated File - ${Math.max(1, Math.round(sizeBytes / 1024))} KB`
          : 'Generated File',
        addedOrder: index,
        filename,
        mimeType,
        encoding: 'base64',
        dataBase64,
        ...(sizeBytes !== undefined ? { sizeBytes } : {}),
      }
    })
    .filter((attachment): attachment is ChatMessageAttachment => attachment !== null)
}

export function parseChatMessageDisplay(content: string): ParsedChatMessageDisplay {
  const lines = content.split('\n')
  const visibleLines: string[] = []
  const attachments: ChatMessageAttachment[] = []
  let lineIndex = 0

  while (lineIndex < lines.length) {
    const line = lines[lineIndex] ?? ''
    const trimmedLine = line.trim()

    if (trimmedLine === '[Attached context]' || trimmedLine === '[Attached images]') {
      const markerType = trimmedLine === '[Attached images]' ? 'uploaded_file' : null
      lineIndex += 1
      while (lineIndex < lines.length) {
        const itemLine = lines[lineIndex] ?? ''
        const trimmedItemLine = itemLine.trim()
        if (!trimmedItemLine) {
          lineIndex += 1
          continue
        }
        if (!trimmedItemLine.startsWith('- ')) break
        const label = trimmedItemLine.slice(2)
        const type = markerType ?? inferLegacyContextAttachmentType(label)
        const attachment = createParsedAttachment(type, label, attachments.length)
        if (attachment) attachments.push(attachment)
        lineIndex += 1
      }
      continue
    }

    if (trimmedLine.startsWith('USER-ATTACHED CONTEXT:')) {
      lineIndex += 1
      while (lineIndex < lines.length) {
        const promptLine = (lines[lineIndex] ?? '').trim()
        if (!promptLine) {
          lineIndex += 1
          continue
        }
        const list = PROMPT_LISTS.find(({ prefix }) => promptLine.startsWith(prefix))
        if (list) {
          const { labels, quoted } = parseAttachmentList(promptLine.slice(list.prefix.length))
          for (const label of labels) {
            const attachment = createParsedAttachment(list.type, label, attachments.length, quoted)
            if (attachment) attachments.push(attachment)
          }
        }
        lineIndex += 1
      }
      continue
    }

    visibleLines.push(line)
    lineIndex += 1
  }

  return {
    content: visibleLines.join('\n').trim(),
    attachments,
  }
}