Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

19.6 KB
Raw Blame
/* eslint-disable @typescript-eslint/no-explicit-any */
import {
  ThreadMessage,
  ContentType,
  MessageStatus,
  ChatCompletionRole,
} from '@janhq/core'
import type { UIMessage } from '@ai-sdk/react'
// Attachments are now handled upstream in newUserThreadContent

type ThreadContent = NonNullable<ThreadMessage['content']>[number]

/**
 * Convert AI SDK UIMessage to Jan's ThreadMessage format.
 * This allows using chatMessages from useChat with ThreadContent component.
 */
export function convertUIMessageToThreadMessage(
  uiMessage: UIMessage,
  threadId: string
): ThreadMessage {
  const content: ThreadContent[] = []

  // Extract text and image parts from UIMessage
  // Use 'any' for parts since the AI SDK types vary between versions
  for (const part of uiMessage.parts as any[]) {
    if (part.type === 'text') {
      content.push({
        type: ContentType.Text,
        text: {
          value: part.text,
          annotations: [],
        },
      })
    } else if (part.type === 'reasoning') {
      // Wrap reasoning in <think> tags for compatibility with existing rendering
      // The reasoning content is in 'reasoning' or 'text' depending on SDK version
      const reasoningText = part.reasoning ?? part.text ?? ''
      const existingText = content.find((c) => c.type === ContentType.Text)
      if (existingText && existingText.text) {
        existingText.text.value = `<think>${reasoningText}</think>${existingText.text.value}`
      } else {
        content.unshift({
          type: ContentType.Text,
          text: {
            value: `<think>${reasoningText}</think>`,
            annotations: [],
          },
        })
      }
    } else if (part.type === 'file' && part.mediaType) {
      const mediaType = part.mediaType as string
      if (mediaType?.startsWith('image/')) {
        content.push({
          type: ContentType.Image,
          image_url: {
            url: part.url,
            detail: 'auto',
          },
        })
      } else if (mediaType === 'audio/wav' || mediaType === 'audio/mpeg') {
        const format = mediaType === 'audio/wav' ? 'wav' : 'mp3'
        const url = part.url as string | undefined
        const data =
          typeof url === 'string' && url.startsWith('data:')
            ? url.slice(url.indexOf(',') + 1)
            : (url ?? '')
        content.push({
          type: ContentType.InputAudio,
          input_audio: { data, format },
        })
      } else if (mediaType?.startsWith('video/')) {
        const url = part.url as string | undefined
        const data =
          typeof url === 'string' && url.startsWith('data:')
            ? url.slice(url.indexOf(',') + 1)
            : (url ?? '')
        content.push({
          type: ContentType.InputVideo,
          input_video: { data, format: mediaType },
        })
      }
    }
  }

  // If no content was extracted, add empty text
  if (content.length === 0) {
    content.push({
      type: ContentType.Text,
      text: {
        value: '',
        annotations: [],
      },
    })
  }

  // Extract tool calls from parts
  const toolCalls = (uiMessage.parts as any[])
    .filter((part) => part.type.startsWith('tool'))
    .map((part) => {
      const toolName = part.type.replace('tool-', '')
      return {
        tool: {
          id: part.toolCallId || part.toolInvocationId,
          type: 'function' as const,
          function: {
            name: toolName,
            arguments:
              typeof part.input === 'string'
                ? part.input
                : JSON.stringify(part.input ?? part.args),
          },
        },
        state: part.state === 'output-available' ? 'completed' : 'pending',
        response: part.output ?? part.result,
      }
    })

  const metadata = uiMessage.metadata as Record<string, unknown> | undefined
  const createdAt =
    metadata?.createdAt instanceof Date ? metadata.createdAt.getTime() : Date.now()

  return {
    id: uiMessage.id,
    object: 'thread.message',
    thread_id: threadId,
    role: uiMessage.role as ThreadMessage['role'],
    content,
    status: MessageStatus.Ready,
    created_at: createdAt,
    completed_at: createdAt,
    metadata: toolCalls.length > 0 ? { tool_calls: toolCalls } : undefined,
  }
}

/**
 * Convert an array of AI SDK UIMessages to Jan's ThreadMessage format.
 */
export function convertUIMessagesToThreadMessages(
  uiMessages: UIMessage[],
  threadId: string
): ThreadMessage[] {
  return uiMessages.map((msg) => convertUIMessageToThreadMessage(msg, threadId))
}

// Define a temporary type for the expected tool result shape (ToolResult as before)
export type ToolResult = {
  content: Array<{
    type?: string
    text?: string
    data?: string
    image_url?: { url: string; detail?: string }
  }>
  error?: string
}

// Reasoning models wrap their chain-of-thought in a tag we strip out: <think>,
// <thought> (Gemma), <thinking>, <reasoning>, plus namespaced variants like
// <mm:think> (MiniMax). Matches an optional `ns:` prefix + a known keyword and
// tolerates attributes on the opening tag. `\1` binds the close tag to the open.
const REASONING_TAG = '(?:[a-zA-Z][a-zA-Z0-9]*:)?(?:think|thinking|thought|reasoning)'
const openReasoningTagRe = () => new RegExp(`<(${REASONING_TAG})(?:\\s[^>]*)?>`, 'i')
const completedReasoningTagRe = () =>
  new RegExp(`<(${REASONING_TAG})(?:\\s[^>]*)?>([\\s\\S]*?)</\\1>`, 'i')

/**
 * Parse reasoning segments from the given text.
 * @param text - The text to parse reasoning from.
 * @returns
 */
export const parseReasoning = (text: string) => {
  // In-progress reasoning: an opening tag whose matching close hasn't streamed yet.
  const openTag = text.match(openReasoningTagRe())
  const hasThinkTag = openTag
    ? !new RegExp(`</${openTag[1]}>`, 'i').test(text)
    : false
  const hasAnalysisChannel =
    text.includes('<|channel|>analysis<|message|>') &&
    !text.includes('<|start|>assistant<|channel|>final<|message|>')

  if (hasThinkTag || hasAnalysisChannel)
    return { reasoningSegment: text, textSegment: '' }

  // Check for completed think tag format
  const thinkMatch = text.match(completedReasoningTagRe())
  if (thinkMatch?.index !== undefined) {
    const splitIndex = thinkMatch.index + thinkMatch[0].length
    return {
      reasoningSegment: text.slice(0, splitIndex),
      textSegment: text.slice(splitIndex),
    }
  }

  // Check for completed analysis channel format
  const analysisMatch = text.match(
    /<\|channel\|>analysis<\|message\|>([\s\S]*?)<\|start\|>assistant<\|channel\|>final<\|message\|>/
  )
  if (analysisMatch?.index !== undefined) {
    const splitIndex = analysisMatch.index + analysisMatch[0].length
    return {
      reasoningSegment: text.slice(0, splitIndex),
      textSegment: text.slice(splitIndex),
    }
  }

  return { reasoningSegment: undefined, textSegment: text }
}

export type ReasoningTextPart = { type: 'reasoning' | 'text'; text: string }

/**
 * Split a raw assistant string into reasoning/text UIMessage parts, pulling out
 * `<think>`/`<thought>`-wrapped reasoning (via {@link parseReasoning}) so it
 * renders in the collapsible reasoning UI instead of inline as literal tags.
 * Shared by the chat message loader and the code agent transcript so both
 * surface reasoning the same way.
 */
export function reasoningPartsFromText(text: string): ReasoningTextPart[] {
  const parts: ReasoningTextPart[] = []
  const { reasoningSegment, textSegment } = parseReasoning(text)

  if (reasoningSegment) {
    // Extract the reasoning text from inside the tag (group 2 = content).
    const completedMatch = reasoningSegment.match(
      new RegExp(`<(${REASONING_TAG})(?:\\s[^>]*)?>([\\s\\S]*)</\\1>`, 'i')
    )
    if (completedMatch) {
      parts.push({ type: 'reasoning', text: completedMatch[2] })
    } else {
      // In-progress reasoning - content after an unclosed reasoning tag.
      const inProgressMatch = reasoningSegment.match(
        new RegExp(`<(${REASONING_TAG})(?:\\s[^>]*)?>([\\s\\S]*)`, 'i')
      )
      if (inProgressMatch) {
        parts.push({ type: 'reasoning', text: inProgressMatch[2] })
      }
    }
  }

  if (textSegment) {
    const trimmedText = textSegment.trim()
    if (trimmedText) parts.push({ type: 'text', text: trimmedText })
  } else if (!reasoningSegment) {
    // No reasoning segment, just add the text as-is.
    parts.push({ type: 'text', text })
  }

  return parts
}

/**
 * Convert Jan's ThreadMessage format to AI SDK UIMessage format.
 * This is used to load existing messages into the AI SDK chat.
 * Tool calls are now part of the content array and will be converted to tool parts.
 */
export function convertThreadMessageToUIMessage(
  threadMessage: ThreadMessage
): UIMessage {
  const parts: any[] = []

  // Process content array - preserve original order (including tool calls)
  for (const content of threadMessage.content || []) {
    if (content.type === 'reasoning' && content.text?.value) {
      // Reasoning content - direct conversion
      parts.push({
        type: 'reasoning',
        text: content.text.value,
      })
    } else if (content.type === 'text' && content.text?.value) {
      // Text content - split out any legacy <think>/<thought> reasoning so it
      // renders in the reasoning UI instead of inline (see reasoningPartsFromText).
      parts.push(...reasoningPartsFromText(content.text.value))
    } else if (content.type === 'image_url' && content.image_url?.url) {
      // The stored record keeps only the url; a data URL names its own type,
      // which a provider that sends base64 with a media type checks against
      // the bytes.
      const url = content.image_url.url
      const declared = /^data:(image\/[a-z0-9.+-]+)[;,]/i.exec(url)?.[1]
      parts.push({
        type: 'file',
        mediaType: declared?.toLowerCase() ?? 'image/jpeg',
        url,
      })
    } else if (content.type === 'input_audio' && content.input_audio?.data) {
      const fmt = content.input_audio.format
      const mediaType = fmt === 'mp3' ? 'audio/mpeg' : 'audio/wav'
      parts.push({
        type: 'file',
        mediaType,
        url: `data:${mediaType};base64,${content.input_audio.data}`,
      })
    } else if (content.type === 'input_video' && content.input_video?.data) {
      const mediaType = content.input_video.format || 'video/mp4'
      parts.push({
        type: 'file',
        mediaType,
        url: `data:${mediaType};base64,${content.input_video.data}`,
      })
    } else if (content.type === 'tool_call') {
      // Handle tool call content items - direct conversion from flat structure
      // Use AI SDK v5 UIToolInvocation format: toolCallId, state: 'output-available'/'input-available'
      // A call that failed, was denied or was stopped has no output; its error
      // is kept beside the content (see `toolErrorsOf`) so it reloads as an
      // error and not as a call that is still running.
      const errorText = (
        threadMessage.metadata as
          | { toolErrors?: Record<string, string> }
          | undefined
      )?.toolErrors?.[content.tool_call_id ?? '']
      if (content.output != null) {
        parts.push({
          type: `tool-${content.tool_name}`,
          toolCallId: content.tool_call_id,
          input: content.input,
          state: 'output-available',
          output: content.output,
        })
      } else if (errorText) {
        parts.push({
          type: `tool-${content.tool_name}`,
          toolCallId: content.tool_call_id,
          input: content.input,
          state: 'output-error',
          errorText,
        })
      } else {
        parts.push({
          type: `tool-${content.tool_name}`,
          toolCallId: content.tool_call_id,
          input: content.input,
          state: 'input-available',
        })
      }
    }
  }

  // BACKWARD COMPATIBILITY: Handle tool calls from metadata (old format)
  // New messages will have tool calls as separate messages with tool_call_id
  const toolCalls = (threadMessage.metadata as any)?.tool_calls
  if (Array.isArray(toolCalls)) {
    for (const tc of toolCalls) {
      // Parse the result from the response.content array
      let result
      if (tc.response?.content) {
        // Extract content from the response
        if (tc.response.content.length === 1 && tc.response.content[0].type === 'text') {
          // Single text content - return as string
          result = tc.response.content[0].text
        } else {
          // Multiple content parts or non-text - return full content array
          result = tc.response.content
        }
      }

      const toolName = tc.tool?.function?.name || tc.name
      let toolInput: unknown
      if (typeof tc.tool?.function?.arguments === 'string') {
        try {
          toolInput = JSON.parse(tc.tool.function.arguments)
        } catch (error) {
          console.warn('Failed to parse tool call arguments; using raw string:', error)
          toolInput = tc.tool.function.arguments
        }
      } else {
        toolInput = tc.tool?.function?.arguments || tc.args
      }
      const toolCallId = tc.tool?.id || tc.id

      // Use AI SDK v5 UIToolInvocation format
      if (result != null || tc.state === 'ready' || tc.state === 'completed' || tc.state === 'result') {
        parts.push({
          type: `tool-${toolName}`,
          toolCallId,
          input: toolInput,
          state: 'output-available',
          output: result,
        })
      } else {
        parts.push({
          type: `tool-${toolName}`,
          toolCallId,
          input: toolInput,
          state: 'input-available',
        })
      }
    }
  }

  // Ensure at least one text part exists
  if (parts.length === 0) {
    parts.push({
      type: 'text',
      text: '',
    })
  }

  return {
    id: threadMessage.id,
    role: threadMessage.role as 'user' | 'assistant' | 'system',
    parts,
    metadata: {
      ...(threadMessage.metadata || {}),
      createdAt: new Date(threadMessage.created_at || Date.now()),
    },
  } as UIMessage
}

export function uiMessageHasMeaningfulContent(message: {
  parts?: any[]
}): boolean {
  if (!message.parts?.length) return false
  for (const part of message.parts) {
    if (!part || typeof part !== 'object') continue
    if (part.type === 'text' && typeof part.text === 'string' && part.text.trim())
      return true
    if (
      part.type === 'reasoning' &&
      ((typeof part.text === 'string' && part.text.trim()) ||
        (typeof part.reasoning === 'string' && part.reasoning.trim()))
    )
      return true
    if (part.type === 'file' && part.url) return true
    if (
      typeof part.type === 'string' &&
      part.type.startsWith('tool-') &&
      (part.input !== undefined || part.args !== undefined ||
        part.output !== undefined || part.result !== undefined)
    )
      return true
  }
  return false
}

export function threadMessageIsEmpty(message: ThreadMessage): boolean {
  if (message.role !== ChatCompletionRole.Assistant) return false
  const content = message.content || []
  if (content.length === 0) return true
  for (const c of content) {
    if (c.type === ContentType.Text || c.type === ContentType.Reasoning) {
      if (c.text?.value && c.text.value.trim()) return false
    } else if (c.type === ContentType.Image && c.image_url?.url) {
      return false
    } else if (c.type === ContentType.InputAudio && c.input_audio?.data) {
      return false
    } else if (c.type === ContentType.InputVideo && c.input_video?.data) {
      return false
    } else if (c.type === ContentType.ToolCall) {
      return false
    }
  }
  return true
}

/**
 * Convert an array of Jan's ThreadMessages to AI SDK UIMessage format.
 * Tool calls are now part of the content array, so no special merging is needed.
 */
export function convertThreadMessagesToUIMessages(
  threadMessages: ThreadMessage[]
): UIMessage[] {
  return threadMessages
    .map(convertThreadMessageToUIMessage)
    .filter((msg): msg is UIMessage => msg !== null)
}

/**
 * The error text of each tool call in `message` that ended in an error (failed,
 * denied, or stopped), by tool call id, for the message's persisted metadata.
 * Such a call has no output to store, so without this it reloads as a call that
 * never finished. Undefined when there is none.
 */
export function toolErrorsOf(
  message: UIMessage
): Record<string, string> | undefined {
  const errors: Record<string, string> = {}
  for (const part of (message.parts ?? []) as any[]) {
    if (
      typeof part?.type === 'string' &&
      part.type.startsWith('tool-') &&
      part.state === 'output-error' &&
      part.toolCallId &&
      part.errorText
    ) {
      errors[part.toolCallId] = part.errorText
    }
  }
  return Object.keys(errors).length > 0 ? errors : undefined
}

/**
 * Extract content from UIMessage parts as separate ThreadContent items.
 * This preserves the structure of multiple text/reasoning/tool call parts instead of combining them.
 *
 * @param message - The UIMessage to extract content from
 * @returns Array of ThreadContent items (including tool calls)
 */
export function extractContentPartsFromUIMessage(message: UIMessage): ThreadContent[] {
  const content: ThreadContent[] = []
  const parts = (message.parts ?? []) as any[]

  for (const part of parts) {
    if (part.type === 'reasoning') {
      // Add reasoning content as separate item
      const reasoningText = part.reasoning ?? part.text ?? ''
      if (reasoningText) {
        const reasoningContent = {
          type: 'reasoning' as ContentType.Reasoning,
          text: {
            value: reasoningText,
            annotations: [],
          },
        }
        content.push(reasoningContent)
      }
    } else if (part.type === 'text') {
      // Add text content as separate item
      const textContent = part.text ?? ''
      if (textContent) {
        content.push({
          type: 'text' as ContentType.Text,
          text: {
            value: textContent,
            annotations: [],
          },
        })
      }
    } else if (part.type === 'file' && part.mediaType) {
      const mediaType = part.mediaType as string
      if (mediaType?.startsWith('image/')) {
        content.push({
          type: 'image_url' as ContentType.Image,
          image_url: {
            url: part.url,
            detail: 'auto',
          },
        })
      } else if (mediaType === 'audio/wav' || mediaType === 'audio/mpeg') {
        const format = mediaType === 'audio/wav' ? 'wav' : 'mp3'
        const url = part.url as string | undefined
        const data =
          typeof url === 'string' && url.startsWith('data:')
            ? url.slice(url.indexOf(',') + 1)
            : (url ?? '')
        content.push({
          type: 'input_audio' as ContentType.InputAudio,
          input_audio: { data, format },
        })
      } else if (mediaType?.startsWith('video/')) {
        const url = part.url as string | undefined
        const data =
          typeof url === 'string' && url.startsWith('data:')
            ? url.slice(url.indexOf(',') + 1)
            : (url ?? '')
        content.push({
          type: 'input_video' as ContentType.InputVideo,
          input_video: { data, format: mediaType },
        })
      }
    } else if (part.type.startsWith('tool-')) {
      // Handle tool call parts - flatten structure to match parts format
      const toolName = (part.type as string).replace('tool-', '')
      const toolCallId = part.toolCallId || part.toolInvocationId
      const input = part.input || part.args
      const output = part.output || part.result

      const toolCallContent = {
        type: 'tool_call' as ContentType.ToolCall,
        tool_call_id: toolCallId,
        tool_name: toolName,
        input: input,
        output: output,
      }
      content.push(toolCallContent)
    }
  }

  // If no content was extracted, add empty text
  if (content.length === 0) {
    content.push({
      type: 'text' as ContentType.Text,
      text: {
        value: '',
        annotations: [],
      },
    })
  }

  return content
}