| import { |
| ATTACHMENT_SAVED_REGEX, |
| MARKDOWN_ATX_HEADING_REGEX, |
| MARKDOWN_BLOCKQUOTE_REGEX, |
| MARKDOWN_BOLD_REGEX, |
| MARKDOWN_CODE_FENCE_REGEX, |
| MARKDOWN_LINK_REGEX, |
| MARKDOWN_LIST_BULLET_REGEX, |
| MARKDOWN_LIST_NUMBERED_REGEX, |
| MARKDOWN_TABLE_SEPARATOR_REGEX, |
| NEWLINE, |
| REASONING_TAGS, |
| SEARCH_SUMMARY_SEPARATOR, |
| SEARCH_SUMMARY_TOTAL_REGEX, |
| TOOL_RESULT_JSON_OPEN_REGEX |
| } from '$lib/constants'; |
| import { |
| AgenticSectionType, |
| AttachmentType, |
| ContinueIntentKind, |
| MessageRole, |
| ToolResultKind |
| } from '$lib/enums'; |
| import type { ApiChatCompletionToolCall } from '$lib/types/api'; |
| import type { |
| DatabaseMessage, |
| DatabaseMessageExtra, |
| DatabaseMessageExtraImageFile |
| } from '$lib/types/database'; |
|
|
| |
| |
| |
| export interface AgenticSection { |
| type: AgenticSectionType; |
| content: string; |
| toolName?: string; |
| toolArgs?: string; |
| toolResult?: string; |
| toolResultExtras?: DatabaseMessageExtra[]; |
| |
| |
| toolCwd?: string; |
| |
| |
| |
| |
| toolCallId?: string; |
| wasInterrupted?: boolean; |
| } |
|
|
| |
| |
| |
| export type ToolResultLine = { |
| text: string; |
| image?: DatabaseMessageExtraImageFile; |
| }; |
|
|
| |
| |
| |
| |
| |
| |
| |
| function deriveSingleTurnSections( |
| message: DatabaseMessage, |
| toolMessages: DatabaseMessage[] = [], |
| streamingToolCalls: ApiChatCompletionToolCall[] = [], |
| isStreaming: boolean = false |
| ): AgenticSection[] { |
| const sections: AgenticSection[] = []; |
|
|
| |
| if (message.reasoningContent) { |
| const toolCalls = parseToolCalls(message.toolCalls); |
| const hasContentAfterReasoning = |
| !!message.content?.trim() || toolCalls.length > 0 || streamingToolCalls.length > 0; |
| const isPending = isStreaming && !hasContentAfterReasoning; |
|
|
| sections.push({ |
| content: message.reasoningContent, |
| type: isPending ? AgenticSectionType.REASONING_PENDING : AgenticSectionType.REASONING, |
| wasInterrupted: !isStreaming && !hasContentAfterReasoning |
| }); |
| } |
|
|
| |
| if (message.content?.trim()) { |
| sections.push({ |
| content: message.content, |
| type: AgenticSectionType.TEXT |
| }); |
| } |
|
|
| |
| const toolCalls = parseToolCalls(message.toolCalls); |
| |
| const toolMsgById = new Map<string, DatabaseMessage>(); |
|
|
| for (const tm of toolMessages) { |
| if (tm.toolCallId && !toolMsgById.has(tm.toolCallId)) { |
| toolMsgById.set(tm.toolCallId, tm); |
| } |
| } |
|
|
| for (const tc of toolCalls) { |
| const resultMsg = tc.id ? toolMsgById.get(tc.id) : undefined; |
| |
| const type = resultMsg |
| ? AgenticSectionType.TOOL_CALL |
| : isStreaming |
| ? AgenticSectionType.TOOL_CALL_PENDING |
| : AgenticSectionType.TOOL_CALL; |
|
|
| sections.push({ |
| content: resultMsg?.content || '', |
| toolArgs: tc.function?.arguments, |
| toolCallId: tc.id, |
| toolCwd: resultMsg?.toolCwd, |
| toolName: tc.function?.name, |
| toolResult: resultMsg?.content, |
| toolResultExtras: resultMsg?.extra, |
| type |
| }); |
| } |
|
|
| |
| const persistedIds = new Set(toolCalls.map((t) => t.id).filter(Boolean)); |
|
|
| for (const tc of streamingToolCalls) { |
| |
| if (tc.id && persistedIds.has(tc.id)) continue; |
|
|
| sections.push({ |
| content: '', |
| toolArgs: tc.function?.arguments, |
| toolCallId: tc.id, |
| toolName: tc.function?.name, |
| type: AgenticSectionType.TOOL_CALL_STREAMING |
| }); |
| } |
|
|
| return sections; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| export function deriveAgenticSections( |
| message: DatabaseMessage, |
| toolMessages: DatabaseMessage[] = [], |
| streamingToolCalls: ApiChatCompletionToolCall[] = [], |
| isStreaming: boolean = false |
| ): AgenticSection[] { |
| const hasAssistantContinuations = toolMessages.some((m) => m.role === MessageRole.ASSISTANT); |
|
|
| if (!hasAssistantContinuations) { |
| return deriveSingleTurnSections(message, toolMessages, streamingToolCalls, isStreaming); |
| } |
|
|
| const sections: AgenticSection[] = []; |
| const firstTurnToolMsgs = collectToolMessages(toolMessages, 0); |
|
|
| sections.push(...deriveSingleTurnSections(message, firstTurnToolMsgs)); |
|
|
| let i = firstTurnToolMsgs.length; |
|
|
| while (i < toolMessages.length) { |
| const msg = toolMessages[i]; |
|
|
| if (msg.role === MessageRole.ASSISTANT) { |
| const turnToolMsgs = collectToolMessages(toolMessages, i + 1); |
| const isLastTurn = i + 1 + turnToolMsgs.length >= toolMessages.length; |
|
|
| sections.push( |
| ...deriveSingleTurnSections( |
| msg, |
| turnToolMsgs, |
| isLastTurn ? streamingToolCalls : [], |
| isLastTurn && isStreaming |
| ) |
| ); |
|
|
| i += 1 + turnToolMsgs.length; |
| } else { |
| i++; |
| } |
| } |
|
|
| return sections; |
| } |
|
|
| |
| |
| |
| |
| |
| export function buildAssistantRawOutput(sections: AgenticSection[]): string { |
| const parts: string[] = []; |
|
|
| for (const section of sections) { |
| switch (section.type) { |
| case AgenticSectionType.REASONING: |
| case AgenticSectionType.REASONING_PENDING: |
| parts.push(`${REASONING_TAGS.START}${NEWLINE}${section.content}${REASONING_TAGS.END}`); |
|
|
| break; |
|
|
| case AgenticSectionType.TEXT: |
| parts.push(section.content); |
|
|
| break; |
|
|
| case AgenticSectionType.TOOL_CALL: |
| case AgenticSectionType.TOOL_CALL_PENDING: |
| case AgenticSectionType.TOOL_CALL_STREAMING: { |
| const callObj: Record<string, unknown> = { name: section.toolName }; |
|
|
| if (section.toolArgs) { |
| try { |
| callObj.arguments = JSON.parse(section.toolArgs); |
| } catch { |
| callObj.arguments = section.toolArgs; |
| } |
| } |
|
|
| parts.push(JSON.stringify(callObj, null, 2)); |
|
|
| if (section.toolResult) { |
| parts.push(`${NEWLINE}${section.toolResult}`); |
| } |
|
|
| break; |
| } |
| } |
| } |
|
|
| return parts.join(`${NEWLINE}${NEWLINE}`); |
| } |
|
|
| |
| |
| |
| function collectToolMessages(messages: DatabaseMessage[], startIndex: number): DatabaseMessage[] { |
| const result: DatabaseMessage[] = []; |
|
|
| for (let i = startIndex; i < messages.length; i++) { |
| if (messages[i].role === MessageRole.TOOL) { |
| result.push(messages[i]); |
| } else { |
| break; |
| } |
| } |
|
|
| return result; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| export function splitSearchSummaryList( |
| text: string, |
| captureTotal: (n: number) => void |
| ): { lines: string[] } { |
| const separatorIndex = text.indexOf(SEARCH_SUMMARY_SEPARATOR); |
| const matchesText = separatorIndex === -1 ? text : text.slice(0, separatorIndex); |
| const summaryText = |
| separatorIndex === -1 ? '' : text.slice(separatorIndex + SEARCH_SUMMARY_SEPARATOR.length); |
| const totalMatch = summaryText.match(SEARCH_SUMMARY_TOTAL_REGEX); |
|
|
| if (totalMatch) { |
| captureTotal(parseInt(totalMatch[1], 10)); |
| } |
|
|
| const lines = matchesText |
| .split(NEWLINE) |
| .map((line) => line.trim()) |
| .filter((line) => line.length > 0); |
|
|
| return { lines }; |
| } |
|
|
| |
| const TOOL_RESULT_LINES_CACHE_MAX_SIZE = 32; |
| const toolResultLinesCache = new Map<string, ToolResultLine[]>(); |
|
|
| |
| |
| |
| |
| |
| export function parseToolResultWithImages( |
| toolResult: string, |
| extras?: DatabaseMessageExtra[] |
| ): ToolResultLine[] { |
| |
| |
| const imageNames = (extras ?? []) |
| .filter((e): e is DatabaseMessageExtraImageFile => e.type === AttachmentType.IMAGE) |
| .map((e) => e.name) |
| .join(NEWLINE); |
| const cacheKey = `${imageNames}:${toolResult}`; |
| const cached = toolResultLinesCache.get(cacheKey); |
|
|
| if (cached !== undefined) return cached; |
|
|
| const lines = toolResult.split(NEWLINE); |
| const result = lines.map((line) => { |
| const match = line.match(ATTACHMENT_SAVED_REGEX); |
|
|
| if (!match || !extras) return { text: line }; |
|
|
| const attachmentName = match[1]; |
| const image = extras.find( |
| (e): e is DatabaseMessageExtraImageFile => |
| e.type === AttachmentType.IMAGE && e.name === attachmentName |
| ); |
|
|
| return { image, text: line }; |
| }); |
|
|
| if (toolResultLinesCache.size >= TOOL_RESULT_LINES_CACHE_MAX_SIZE) { |
| toolResultLinesCache.delete(toolResultLinesCache.keys().next().value!); |
| } |
|
|
| toolResultLinesCache.set(cacheKey, result); |
|
|
| return result; |
| } |
|
|
| |
| const CLASSIFY_CACHE_MAX_SIZE = 32; |
| const classifyCache = new Map<string, ToolResultKind>(); |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| export function classifyToolResult(content: string | undefined): ToolResultKind { |
| if (!content) return ToolResultKind.TEXT; |
|
|
| const cached = classifyCache.get(content); |
|
|
| if (cached !== undefined) return cached; |
|
|
| const trimmed = content.trim(); |
|
|
| if (!trimmed) return ToolResultKind.TEXT; |
|
|
| let result: ToolResultKind = ToolResultKind.TEXT; |
|
|
| |
| if (TOOL_RESULT_JSON_OPEN_REGEX.test(trimmed)) { |
| try { |
| JSON.parse(trimmed); |
| result = ToolResultKind.JSON; |
| } catch (error) { |
| console.error('[agentic] tool result looked like JSON but failed to parse:', error); |
| } |
| } |
|
|
| if (result === ToolResultKind.TEXT && looksLikeMarkdown(trimmed)) { |
| result = ToolResultKind.MARKDOWN; |
| } |
|
|
| if (classifyCache.size >= CLASSIFY_CACHE_MAX_SIZE) { |
| classifyCache.delete(classifyCache.keys().next().value!); |
| } |
|
|
| classifyCache.set(content, result); |
|
|
| return result; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| function looksLikeMarkdown(content: string): boolean { |
| |
| if (MARKDOWN_CODE_FENCE_REGEX.test(content)) return true; |
|
|
| const lines = content.split(NEWLINE); |
|
|
| for (const line of lines) { |
| if (MARKDOWN_ATX_HEADING_REGEX.test(line)) return true; |
|
|
| if (MARKDOWN_BLOCKQUOTE_REGEX.test(line)) return true; |
|
|
| if (MARKDOWN_LIST_BULLET_REGEX.test(line)) return true; |
|
|
| if (MARKDOWN_LIST_NUMBERED_REGEX.test(line)) return true; |
| } |
|
|
| |
| if (MARKDOWN_LINK_REGEX.test(content)) return true; |
|
|
| if (MARKDOWN_BOLD_REGEX.test(content)) return true; |
|
|
| |
| if (lines.length >= 2) { |
| const head = lines[0]; |
| const sep = lines[1]; |
|
|
| if (head.includes('|') && MARKDOWN_TABLE_SEPARATOR_REGEX.test(sep)) return true; |
| } |
|
|
| return false; |
| } |
|
|
| |
| const TOOL_CALLS_CACHE_MAX_SIZE = 64; |
| const toolCallsParseCache = new Map<string, ApiChatCompletionToolCall[]>(); |
|
|
| |
| |
| |
| |
| |
| function parseToolCalls(toolCallsJson?: string): ApiChatCompletionToolCall[] { |
| if (!toolCallsJson) return []; |
|
|
| const cached = toolCallsParseCache.get(toolCallsJson); |
|
|
| if (cached) return cached; |
|
|
| let result: ApiChatCompletionToolCall[]; |
|
|
| try { |
| const parsed = JSON.parse(toolCallsJson); |
|
|
| result = Array.isArray(parsed) ? parsed : []; |
| } catch { |
| result = []; |
| } |
|
|
| if (toolCallsParseCache.size >= TOOL_CALLS_CACHE_MAX_SIZE) { |
| toolCallsParseCache.delete(toolCallsParseCache.keys().next().value!); |
| } |
|
|
| toolCallsParseCache.set(toolCallsJson, result); |
|
|
| return result; |
| } |
|
|
| |
| |
| |
| export function hasAgenticContent( |
| message: DatabaseMessage, |
| toolMessages: DatabaseMessage[] = [] |
| ): boolean { |
| if (message.toolCalls) { |
| const tc = parseToolCalls(message.toolCalls); |
|
|
| if (tc.length > 0) return true; |
| } |
|
|
| return toolMessages.length > 0; |
| } |
|
|
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| export type ContinueIntent = |
| | { kind: ContinueIntentKind.APPEND_TEXT } |
| | { kind: ContinueIntentKind.RERUN_TURN; truncateAfter: number } |
| | { kind: ContinueIntentKind.NEXT_TURN; truncateAfter: number }; |
|
|
| |
| |
| |
| |
| export function classifyContinueIntent(messages: DatabaseMessage[], idx: number): ContinueIntent { |
| const target = messages[idx]; |
|
|
| |
| if (!target || target.role !== MessageRole.ASSISTANT) { |
| return { kind: ContinueIntentKind.APPEND_TEXT }; |
| } |
|
|
| const hasToolCalls = parseToolCalls(target.toolCalls).length > 0; |
|
|
| if (!hasToolCalls) { |
| return { kind: ContinueIntentKind.APPEND_TEXT }; |
| } |
|
|
| |
| |
| |
| let lastTrailingTool = idx; |
|
|
| for (let i = idx + 1; i < messages.length; i++) { |
| if (messages[i].role === MessageRole.TOOL) { |
| lastTrailingTool = i; |
| } else { |
| break; |
| } |
| } |
|
|
| if (lastTrailingTool > idx) { |
| return { kind: ContinueIntentKind.NEXT_TURN, truncateAfter: lastTrailingTool }; |
| } |
|
|
| return { kind: ContinueIntentKind.RERUN_TURN, truncateAfter: idx - 1 }; |
| } |
|
|