import type { BaseStream } from "@langchain/langgraph-sdk/react"; import { apiFetch } from "../api"; import type { AgentThreadState } from "../threads"; import { urlOfArtifact } from "./utils"; export async function loadArtifactContent({ filepath, threadId, isMock, publicShareCode, }: { filepath: string; threadId: string; isMock?: boolean; publicShareCode?: string; }) { let enhancedFilepath = filepath; if (filepath.endsWith(".skill")) { enhancedFilepath = filepath + "/SKILL.md"; } const url = urlOfArtifact({ filepath: enhancedFilepath, threadId, isMock, publicShareCode }); const response = await apiFetch(url); const text = await response.text(); if (!response.ok) { let detail = text.trim(); try { const parsed = JSON.parse(text) as { detail?: unknown; message?: unknown }; const parsedDetail = typeof parsed.detail === "string" ? parsed.detail : typeof parsed.message === "string" ? parsed.message : ""; if (parsedDetail) { detail = parsedDetail; } } catch { // Keep the raw response text as the diagnostic detail. } throw new Error( `Failed to load artifact (${response.status})${detail ? `: ${detail}` : ""}`, ); } return { content: text, url }; } export function loadArtifactContentFromToolCall({ url: urlString, thread, }: { url: string; thread: BaseStream; }) { const url = new URL(urlString); const toolCallId = url.searchParams.get("tool_call_id"); const messageId = url.searchParams.get("message_id"); if (messageId && toolCallId) { const message = thread.messages.find((message) => message.id === messageId); if (message?.type === "ai" && message.tool_calls) { const toolCall = message.tool_calls.find( (toolCall) => toolCall.id === toolCallId, ); if (toolCall) { return toolCall.args.content; } } } }