@discomedia/utils 1.0.78 → 1.0.79

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/index-frontend.ts", "../src/types/index.ts", "../src/types/llm-types.ts", "../src/llm-openai.ts", "../src/llm-config.ts", "../src/json-tools.ts", "../src/llm-utils.ts", "../src/llm-images.ts", "../src/llm-deepseek.ts", "../src/market-time.ts", "../src/market-hours.ts"],
4
- "sourcesContent": ["/* Front-end only exports.\nImport these with `import { disco } from 'disco-core/frontend'` \n*/\n\n\nimport * as Types from './types';\nimport * as llm from './llm-openai';\nimport * as llmImages from './llm-images';\nimport * as deepseek from './llm-deepseek';\nimport * as time from './market-time';\n\n// Re-export all types\nexport * from './types';\nexport { supportsTemperature, uploadVisionFile } from './llm-openai';\nexport { OPENAI_MODELS, OPENROUTER_MODELS } from './types/llm-types';\n\nexport const disco = {\n types: Types,\n llm: {\n call: llm.makeLLMCall,\n uploadVisionFile: llm.uploadVisionFile,\n seek: deepseek.makeDeepseekCall,\n images: llmImages.makeImagesCall,\n },\n time,\n};\n", "export * from './alpaca-types';\nexport * from './market-time-types';\nexport * from './ta-types';\nexport * from './llm-types';\nexport * from './logging-types';", "// openai-types.ts\nimport type {\n ChatCompletionMessageParam,\n ChatCompletionTool,\n ChatCompletionMessageToolCall,\n} from 'openai/resources/chat/completions';\nimport type { ImageGenerateParams, ImageModel } from 'openai/resources/images';\nimport type { ResponseFormatTextJSONSchemaConfig, ResponseInputImage } from 'openai/resources/responses/responses';\nimport type { ZodType } from 'zod';\n\n/**\n * Represents OpenAI models\n */\nexport const OPENAI_MODELS = [\n 'gpt-5.6',\n 'gpt-5.6-sol',\n 'gpt-5.6-terra',\n 'gpt-5.6-luna',\n 'gpt-5',\n 'gpt-5-mini',\n 'gpt-5.4-mini',\n 'gpt-5.4-nano',\n 'gpt-5-nano',\n 'gpt-5.1',\n 'gpt-5.4',\n 'gpt-5.5',\n 'gpt-5.5-pro',\n 'gpt-5.2',\n 'gpt-5.2-pro',\n 'gpt-5.1-codex',\n 'gpt-5.1-codex-max',\n] as const;\n\nexport type OpenAIModel = (typeof OPENAI_MODELS)[number];\n\n/**\n * Type guard to check if a model is a supported direct OpenAI model.\n */\nexport function isOpenAIModel(model: string): model is OpenAIModel {\n return OPENAI_MODELS.includes(model as OpenAIModel);\n}\n\n/**\n * Represents OpenAI image models.\n */\nexport const OPENAI_IMAGE_MODELS = [\n 'gpt-image-2',\n 'gpt-image-2-2026-04-21',\n 'gpt-image-1.5',\n 'gpt-image-1',\n 'gpt-image-1-mini',\n 'chatgpt-image-latest',\n 'dall-e-2',\n 'dall-e-3',\n] as const satisfies readonly ImageModel[];\n\nexport type OpenAIImageModel = (typeof OPENAI_IMAGE_MODELS)[number];\n\n/**\n * Type guard to check if a model is a supported OpenAI image model.\n */\nexport function isOpenAIImageModel(model: string): model is OpenAIImageModel {\n return OPENAI_IMAGE_MODELS.includes(model as OpenAIImageModel);\n}\n\n/**\n * Represents Deepseek models\n */\nexport type DeepseekModel = 'deepseek-chat' | 'deepseek-reasoner';\n\n/**\n * Represents OpenRouter models\n */\nexport const OPENROUTER_MODELS = [\n 'openai/gpt-5',\n 'openai/gpt-5-mini',\n 'openai/gpt-5.4-mini',\n 'openai/gpt-5.4-nano',\n 'openai/gpt-5-nano',\n 'openai/gpt-5.1',\n 'openai/gpt-5.4',\n 'openai/gpt-5.4-pro',\n 'openai/gpt-5.5',\n 'openai/gpt-5.5-pro',\n 'openai/gpt-5.2',\n 'openai/gpt-5.2-pro',\n 'openai/gpt-5.1-codex',\n 'openai/gpt-5.1-codex-max',\n 'openai/gpt-oss-120b',\n 'z.ai/glm-4.5',\n 'z.ai/glm-4.5-air',\n 'google/gemini-2.5-flash',\n 'google/gemini-2.5-flash-lite',\n 'deepseek/deepseek-r1-0528',\n 'deepseek/deepseek-chat-v3-0324',\n] as const;\n\nexport type OpenRouterModel = (typeof OPENROUTER_MODELS)[number];\n\n/**\n * Represents pricing information for OpenRouter models\n */\nexport interface OpenRouterPricing {\n input: number; // Cost per 1M input tokens\n output: number; // Cost per 1M output tokens\n context?: number; // Max context tokens\n}\n\n/**\n * Represents all supported LLM models\n */\nexport type LLMModel = OpenAIModel | DeepseekModel | OpenRouterModel;\n\n/**\n * Type guard to check if a model is an OpenRouter model\n */\nexport function isOpenRouterModel(model: string): model is OpenRouterModel {\n return OPENROUTER_MODELS.includes(model as OpenRouterModel);\n}\n\n/**\n * Represents the usage of the LLM.\n */\nexport interface LLMUsage {\n prompt_tokens: number;\n completion_tokens: number;\n reasoning_tokens?: number;\n provider: string;\n model: LLMModel;\n cache_hit_tokens?: number;\n cache_write_tokens?: number;\n cost: number;\n}\n\n/**\n * Represents the options for the LLM.\n */\nexport interface LLMOptions {\n model?: LLMModel;\n temperature?: number;\n top_p?: number;\n frequency_penalty?: number;\n presence_penalty?: number;\n max_completion_tokens?: number;\n tools?: ChatCompletionTool[];\n developerPrompt?: string;\n context?: ChatCompletionMessageParam[];\n store?: boolean;\n reasoning_effort?: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';\n reasoning_mode?: 'standard' | 'pro';\n reasoning_context?: 'auto' | 'current_turn' | 'all_turns';\n metadata?: Record<string, string>;\n parallel_tool_calls?: boolean;\n service_tier?: 'auto' | 'default' | 'flex' | 'priority';\n apiKey?: string;\n}\n\n/**\n * Represents the response from the LLM.\n */\nexport interface LLMResponse<T> {\n response: T;\n usage: LLMUsage;\n tool_calls?: ChatCompletionMessageToolCall[];\n}\n\n/**\n * Represents the format of the OpenAI response.\n */\nexport type OpenAIResponseFormat = 'text' | 'json' | ResponseFormatTextJSONSchemaConfig;\n\n/**\n * Represents schema input for structured outputs in OpenAI calls.\n * Can be either a JSON Schema object or a Zod schema.\n */\nexport type OpenAISchemaInput = ResponseFormatTextJSONSchemaConfig['schema'] | ZodType;\n\n/**\n * Supported image detail levels for OpenAI Responses vision inputs.\n */\nexport type OpenAIImageDetail = ResponseInputImage['detail'];\n\n/**\n * A remote image URL to analyze.\n */\nexport interface OpenAIImageURLInput {\n url: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * A base64-encoded image to analyze.\n * If `base64` is a raw base64 string, `mimeType` is used to create a data URL.\n */\nexport interface OpenAIImageBase64Input {\n base64: string;\n mimeType?: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * A fully formed data URL to analyze.\n */\nexport interface OpenAIImageDataURLInput {\n dataUrl: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * An already-uploaded OpenAI file ID to analyze.\n */\nexport interface OpenAIImageFileIDInput {\n fileId: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * A local file path to upload for vision analysis in Node.js environments.\n */\nexport interface OpenAIImageFilePathInput {\n filePath: string;\n filename?: string;\n mimeType?: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * Vision image input accepted by the OpenAI Responses helper.\n */\nexport type OpenAIImageInput =\n | OpenAIImageURLInput\n | OpenAIImageBase64Input\n | OpenAIImageDataURLInput\n | OpenAIImageFileIDInput\n | OpenAIImageFilePathInput;\n\n/**\n * Represents the options for the OpenAI Images API.\n * Extends the official ImageGenerateParams but with more user-friendly option names.\n */\nexport interface ImageGenerationOptions {\n model?: DiscoImageModel;\n size?: ImageGenerateParams['size'];\n outputFormat?: 'jpeg' | 'png' | 'webp';\n compression?: number;\n quality?: ImageGenerateParams['quality'];\n count?: number | null;\n apiKey?: string;\n background?: ImageGenerateParams['background'];\n moderation?: ImageGenerateParams['moderation'];\n /**\n * Optional multimodal LLM to pair with image outputs (e.g., gpt-5.4).\n */\n visionModel?: LLMModel;\n}\n\nexport type DiscoImageModel = OpenAIImageModel;\n\n/**\n * Context message for conversation history\n */\nexport interface ContextMessage {\n role: 'user' | 'assistant' | 'system' | 'developer';\n content: string;\n}\n\n\n// Re-export OpenAI types for convenience\nexport type { ImageModel, ImageGenerateParams } from 'openai/resources/images';\nexport type { ImagesResponse, Image } from 'openai/resources/images';\nexport type { Tool } from 'openai/resources/responses/responses';\n", "// llm-openai.ts\n\nimport OpenAI from 'openai';\nimport { zodTextFormat } from 'openai/helpers/zod';\nimport type { ZodType } from 'zod';\n\nimport type {\n Tool,\n ResponseInput,\n EasyInputMessage,\n ResponseInputImage,\n ResponseInputText,\n} from 'openai/resources/responses/responses';\n\nimport { calculateCost, DEFAULT_MODEL } from './llm-config';\nimport { parseResponse, normalizeModelName } from './llm-utils';\nimport { isOpenAIModel } from './types';\nimport type {\n LLMResponse,\n LLMOptions,\n LLMModel,\n OpenAIResponseFormat,\n ContextMessage,\n OpenAISchemaInput,\n OpenAIImageInput,\n OpenAIImageDetail,\n} from './types';\nimport type {\n ResponseCreateParamsNonStreaming,\n ResponseOutputItem,\n ResponseFunctionToolCall,\n ResponseCodeInterpreterToolCall,\n ResponseOutputMessage,\n ResponseOutputText,\n ResponseFormatTextJSONSchemaConfig,\n} from 'openai/resources/responses/responses';\n\nexport const DEFAULT_OPTIONS: LLMOptions = {\n model: DEFAULT_MODEL,\n parallel_tool_calls: false,\n};\n\nconst DEFAULT_IMAGE_MIME_TYPE = 'image/webp';\n\n/**\n * Checks if the given direct OpenAI model supports the temperature parameter.\n * @param model The model to check.\n * @returns True if the model supports the temperature parameter, false otherwise.\n */\nexport function supportsTemperature(_model: string): boolean {\n return false;\n}\n\nfunction isZodSchema(schema: OpenAISchemaInput): schema is ZodType {\n return typeof schema === 'object' && schema !== null && 'safeParse' in schema;\n}\n\nfunction buildJsonSchemaFormat(\n schema: OpenAISchemaInput,\n schemaName: string,\n schemaDescription?: string,\n schemaStrict?: boolean\n): ResponseFormatTextJSONSchemaConfig {\n if (isZodSchema(schema)) {\n const zodFormat = zodTextFormat(\n schema,\n schemaName,\n schemaDescription\n ? {\n description: schemaDescription,\n }\n : undefined\n );\n\n return {\n type: 'json_schema',\n name: zodFormat.name,\n schema: zodFormat.schema,\n ...(zodFormat.description ? { description: zodFormat.description } : {}),\n ...(schemaStrict !== undefined ? { strict: schemaStrict } : { strict: zodFormat.strict }),\n };\n }\n\n return {\n type: 'json_schema',\n name: schemaName,\n schema,\n ...(schemaDescription ? { description: schemaDescription } : {}),\n ...(schemaStrict !== undefined ? { strict: schemaStrict } : {}),\n };\n}\n\nfunction resolveOpenAIApiKey(apiKey?: string): string {\n const resolvedApiKey = apiKey || process.env.OPENAI_API_KEY;\n\n if (!resolvedApiKey) {\n throw new Error('OpenAI API key is not provided and OPENAI_API_KEY environment variable is not set');\n }\n\n return resolvedApiKey;\n}\n\nfunction createOpenAIClient(apiKey: string): OpenAI {\n return new OpenAI({\n apiKey,\n });\n}\n\nfunction normalizeImageDataUrl(imageData: string, mimeType = DEFAULT_IMAGE_MIME_TYPE): string {\n return imageData.startsWith('data:') ? imageData : `data:${mimeType};base64,${imageData}`;\n}\n\nfunction getFilenameFromPath(filePath: string): string {\n const normalizedPath = filePath.replace(/\\\\/g, '/');\n const pathSegments = normalizedPath.split('/');\n const filename = pathSegments[pathSegments.length - 1];\n\n if (!filename) {\n throw new Error(`Could not determine a filename from file path: ${filePath}`);\n }\n\n return filename;\n}\n\nfunction inferImageMimeType(filePath: string): string | undefined {\n const normalizedPath = filePath.toLowerCase();\n\n if (normalizedPath.endsWith('.png')) {\n return 'image/png';\n }\n\n if (normalizedPath.endsWith('.jpg') || normalizedPath.endsWith('.jpeg')) {\n return 'image/jpeg';\n }\n\n if (normalizedPath.endsWith('.webp')) {\n return 'image/webp';\n }\n\n if (normalizedPath.endsWith('.gif')) {\n return 'image/gif';\n }\n\n return undefined;\n}\n\nasync function readLocalFileBytes(filePath: string): Promise<Uint8Array> {\n try {\n const dynamicImport = new Function('specifier', 'return import(specifier);') as (\n specifier: string\n ) => Promise<{ readFile: (path: string) => Promise<Uint8Array> }>;\n const { readFile } = await dynamicImport('node:fs/promises');\n\n return await readFile(filePath);\n } catch {\n throw new Error('Local image file uploads require a Node.js runtime with access to node:fs/promises');\n }\n}\n\nasync function uploadVisionFileFromPath(\n openai: OpenAI,\n filePath: string,\n filename?: string,\n mimeType?: string\n): Promise<string> {\n const fileBytes = await readLocalFileBytes(filePath);\n const resolvedFilename = filename || getFilenameFromPath(filePath);\n const resolvedMimeType = mimeType || inferImageMimeType(filePath);\n const uploadableFile = await OpenAI.toFile(\n fileBytes,\n resolvedFilename,\n resolvedMimeType ? { type: resolvedMimeType } : undefined\n );\n\n const uploadedFile = await openai.files.create({\n file: uploadableFile,\n purpose: 'vision',\n });\n\n return uploadedFile.id;\n}\n\nfunction collectImageInputs(\n image: OpenAIImageInput | undefined,\n images: OpenAIImageInput[] | undefined,\n imageBase64: string | undefined\n): OpenAIImageInput[] {\n const collectedImages: OpenAIImageInput[] = [];\n\n if (image) {\n collectedImages.push(image);\n }\n\n if (images && images.length > 0) {\n collectedImages.push(...images);\n }\n\n if (imageBase64) {\n collectedImages.push({ base64: imageBase64 });\n }\n\n return collectedImages;\n}\n\nfunction hasLocalFileImage(images: OpenAIImageInput[]): boolean {\n return images.some((image) => 'filePath' in image);\n}\n\nasync function buildImageContentPart(\n image: OpenAIImageInput,\n defaultDetail: OpenAIImageDetail,\n openai?: OpenAI\n): Promise<ResponseInputImage> {\n const detail = image.detail ?? defaultDetail;\n\n if ('url' in image) {\n return {\n type: 'input_image',\n detail,\n image_url: image.url,\n };\n }\n\n if ('dataUrl' in image) {\n return {\n type: 'input_image',\n detail,\n image_url: image.dataUrl,\n };\n }\n\n if ('base64' in image) {\n return {\n type: 'input_image',\n detail,\n image_url: normalizeImageDataUrl(image.base64, image.mimeType),\n };\n }\n\n if ('fileId' in image) {\n return {\n type: 'input_image',\n detail,\n file_id: image.fileId,\n };\n }\n\n if (!openai) {\n throw new Error('A local image file path was provided, but no OpenAI client is available to upload it');\n }\n\n const fileId = await uploadVisionFileFromPath(openai, image.filePath, image.filename, image.mimeType);\n return {\n type: 'input_image',\n detail,\n file_id: fileId,\n };\n}\n\nasync function buildPromptContent(\n input: string,\n imageInputs: OpenAIImageInput[],\n imageDetail: OpenAIImageDetail,\n openai?: OpenAI\n): Promise<string | Array<ResponseInputText | ResponseInputImage>> {\n if (imageInputs.length === 0) {\n return input;\n }\n\n const imageContent = await Promise.all(imageInputs.map((image) => buildImageContentPart(image, imageDetail, openai)));\n\n return [{ type: 'input_text', text: input }, ...imageContent];\n}\n\nexport async function uploadVisionFile(\n filePath: string,\n options: {\n apiKey?: string;\n filename?: string;\n mimeType?: string;\n } = {}\n): Promise<string> {\n const resolvedApiKey = resolveOpenAIApiKey(options.apiKey);\n const openai = createOpenAIClient(resolvedApiKey);\n\n return await uploadVisionFileFromPath(openai, filePath, options.filename, options.mimeType);\n}\n\n/**\n * Makes a call to OpenAI's Responses API for more advanced use cases with built-in tools.\n *\n * This function provides access to the Responses API which supports:\n * - Built-in tools (web search, file search, computer use, code interpreter, image generation)\n * - Background processing\n * - Conversation state management\n * - GPT-5 reasoning controls\n *\n * @example\n * // Basic text response\n * const response = await makeResponsesAPICall('What is the weather like?');\n *\n * @example\n * // With web search tool\n * const response = await makeResponsesAPICall('Latest news about AI', {\n * tools: [{ type: 'web_search_preview' }]\n * });\n *\n * @param input - The input content. Can be:\n * - A string for simple text prompts\n * - An array of input items for complex/multi-modal content\n * @param options - Configuration options for the Responses API\n * @returns Promise<LLMResponse<T>> - The response in the same format as makeLLMCall\n * @throws Error if the API call fails\n */\nexport const makeResponsesAPICall = async <T = string>(\n input: string | ResponseCreateParamsNonStreaming['input'],\n options: Omit<ResponseCreateParamsNonStreaming, 'input' | 'model'> & {\n apiKey?: string;\n model?: string;\n } = {}\n): Promise<LLMResponse<T>> => {\n const normalizedModel = normalizeModelName(options.model || DEFAULT_MODEL);\n if (!isOpenAIModel(normalizedModel)) {\n throw new Error(`Unsupported OpenAI model: ${normalizedModel}. Please use a supported GPT-5 model.`);\n }\n\n const apiKey = resolveOpenAIApiKey(options.apiKey);\n const openai = createOpenAIClient(apiKey);\n\n // Remove apiKey from options before creating request body\n const { apiKey: _, model: __, ...cleanOptions } = options;\n\n const requestBody: ResponseCreateParamsNonStreaming = {\n model: normalizedModel,\n input,\n ...cleanOptions,\n };\n\n // Make the API call to the Responses endpoint\n const response = await openai.responses.create(requestBody);\n const cacheHitTokens = response.usage?.input_tokens_details?.cached_tokens || 0;\n const cacheWriteTokens = response.usage?.input_tokens_details?.cache_write_tokens || 0;\n\n // Extract tool calls from the output\n const toolCalls = response.output\n ?.filter((item: ResponseOutputItem): item is ResponseFunctionToolCall => item.type === 'function_call')\n .map((toolCall: ResponseFunctionToolCall) => ({\n id: toolCall.call_id,\n type: 'function' as const,\n function: {\n name: toolCall.name,\n arguments: toolCall.arguments,\n },\n }));\n\n // Extract code interpreter outputs if present\n const codeInterpreterCalls = response.output?.filter(\n (item: ResponseOutputItem): item is ResponseCodeInterpreterToolCall => item.type === 'code_interpreter_call'\n );\n let codeInterpreterOutputs: ResponseCodeInterpreterToolCall['outputs'] | undefined = undefined;\n if (codeInterpreterCalls && codeInterpreterCalls.length > 0) {\n // Each code_interpreter_call has an 'outputs' array property\n codeInterpreterOutputs = codeInterpreterCalls.flatMap((ci) => {\n // Return outputs if present, otherwise empty array\n if (ci.outputs) return ci.outputs;\n return [];\n });\n }\n\n // Handle tool calls differently\n if (toolCalls && toolCalls.length > 0) {\n return {\n response: {\n tool_calls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n arguments: JSON.parse(tc.function.arguments),\n })),\n } as T,\n usage: {\n prompt_tokens: response.usage?.input_tokens || 0,\n completion_tokens: response.usage?.output_tokens || 0,\n reasoning_tokens: response.usage?.output_tokens_details?.reasoning_tokens || 0,\n provider: 'openai',\n model: normalizedModel,\n cache_hit_tokens: cacheHitTokens,\n cache_write_tokens: cacheWriteTokens,\n cost: calculateCost(\n 'openai',\n normalizedModel,\n response.usage?.input_tokens || 0,\n response.usage?.output_tokens || 0,\n response.usage?.output_tokens_details?.reasoning_tokens || 0,\n cacheHitTokens,\n cacheWriteTokens\n ),\n },\n tool_calls: toolCalls,\n ...(codeInterpreterOutputs ? { code_interpreter_outputs: codeInterpreterOutputs } : {}),\n };\n }\n\n // Extract text content from the response output\n const textContent =\n response.output\n ?.filter((item: ResponseOutputItem): item is ResponseOutputMessage => item.type === 'message')\n .map((item: ResponseOutputMessage) =>\n item.content\n .filter((content): content is ResponseOutputText => content.type === 'output_text')\n .map((content) => content.text)\n .join('')\n )\n .join('') || '';\n\n // Determine the format for parsing the response\n let parsingFormat: OpenAIResponseFormat = 'text';\n const requestedFormat = requestBody.text?.format;\n if (requestedFormat?.type === 'json_object') {\n parsingFormat = 'json';\n } else if (requestedFormat?.type === 'json_schema') {\n parsingFormat = requestedFormat;\n }\n\n // Handle regular responses\n const parsedResponse = await parseResponse<T>(textContent, parsingFormat);\n if (parsedResponse === null) {\n throw new Error('Failed to parse response from Responses API');\n }\n\n return {\n response: parsedResponse,\n usage: {\n prompt_tokens: response.usage?.input_tokens || 0,\n completion_tokens: response.usage?.output_tokens || 0,\n reasoning_tokens: response.usage?.output_tokens_details?.reasoning_tokens || 0,\n provider: 'openai',\n model: normalizedModel,\n cache_hit_tokens: cacheHitTokens,\n cache_write_tokens: cacheWriteTokens,\n cost: calculateCost(\n 'openai',\n normalizedModel,\n response.usage?.input_tokens || 0,\n response.usage?.output_tokens || 0,\n response.usage?.output_tokens_details?.reasoning_tokens || 0,\n cacheHitTokens,\n cacheWriteTokens\n ),\n },\n tool_calls: toolCalls,\n ...(codeInterpreterOutputs ? { code_interpreter_outputs: codeInterpreterOutputs } : {}),\n };\n};\n\n/**\n * Makes a call to the OpenAI Responses API for advanced use cases with built-in tools.\n *\n * @param input The text prompt to send to the model (e.g., \"What's in this image?\")\n * @param options The options for the Responses API call, including optional image data and context.\n * @return A promise that resolves to the response from the Responses API.\n *\n * @example\n * // With conversation context\n * const response = await makeLLMCall(\"What did I ask about earlier?\", {\n * context: [\n * { role: 'user', content: 'What is the capital of France?' },\n * { role: 'assistant', content: 'The capital of France is Paris.' }\n * ]\n * });\n */\nexport async function makeLLMCall<T = string>(\n input: string,\n options: {\n apiKey?: string;\n model?: LLMModel;\n responseFormat?: OpenAIResponseFormat;\n schema?: OpenAISchemaInput;\n schemaName?: string;\n schemaDescription?: string;\n schemaStrict?: boolean;\n tools?: Tool[];\n useCodeInterpreter?: boolean;\n useWebSearch?: boolean;\n image?: OpenAIImageInput;\n images?: OpenAIImageInput[];\n imageBase64?: string;\n imageDetail?: OpenAIImageDetail;\n context?: ContextMessage[];\n reasoningEffort?: LLMOptions['reasoning_effort'];\n reasoningMode?: LLMOptions['reasoning_mode'];\n reasoningContext?: LLMOptions['reasoning_context'];\n } = {}\n): Promise<LLMResponse<T>> {\n const {\n apiKey,\n model = DEFAULT_MODEL,\n responseFormat = 'text',\n schema,\n schemaName = 'response',\n schemaDescription,\n schemaStrict,\n tools,\n useCodeInterpreter = false,\n useWebSearch = false,\n image,\n images,\n imageBase64,\n imageDetail = 'high',\n context,\n reasoningEffort,\n reasoningMode,\n reasoningContext,\n } = options;\n\n // Validate model\n const normalizedModel = normalizeModelName(model);\n if (!isOpenAIModel(normalizedModel)) {\n throw new Error(`Unsupported OpenAI model: ${normalizedModel}. Please use a supported GPT-5 model.`);\n }\n\n const resolvedApiKey = resolveOpenAIApiKey(apiKey);\n const imageInputs = collectImageInputs(image, images, imageBase64);\n const openai = hasLocalFileImage(imageInputs) ? createOpenAIClient(resolvedApiKey) : undefined;\n const promptContent = await buildPromptContent(input, imageInputs, imageDetail, openai);\n\n // Process input for conversation context and image analysis\n let processedInput: string | ResponseInput;\n\n if (context && context.length > 0) {\n // Build conversation array with context\n const conversationMessages: EasyInputMessage[] = [];\n\n // Add context messages\n for (const contextMsg of context) {\n conversationMessages.push({\n role: contextMsg.role,\n content: contextMsg.content,\n type: 'message',\n });\n }\n\n // Add current input message\n if (imageInputs.length > 0) {\n // Current message includes text and one or more images\n conversationMessages.push({\n role: 'user',\n content: promptContent,\n type: 'message',\n });\n } else {\n // Current message is just text\n conversationMessages.push({\n role: 'user',\n content: input,\n type: 'message',\n });\n }\n\n processedInput = conversationMessages;\n } else if (imageInputs.length > 0) {\n // No context, but has image(s)\n processedInput = [\n {\n role: 'user',\n content: promptContent,\n type: 'message',\n },\n ];\n } else {\n // No context, no image - simple string input\n processedInput = input;\n }\n\n // Build the options object for makeResponsesAPICall\n let responsesOptions: Parameters<typeof makeResponsesAPICall>[1] = {\n apiKey: resolvedApiKey,\n model: normalizedModel,\n parallel_tool_calls: false,\n tools,\n };\n\n // Only include temperature if the model supports it\n if (supportsTemperature(normalizedModel)) {\n responsesOptions.temperature = 0.2;\n }\n\n if (reasoningEffort || reasoningMode || reasoningContext) {\n responsesOptions.reasoning = {\n ...(reasoningEffort ? { effort: reasoningEffort } : {}),\n ...(reasoningMode ? { mode: reasoningMode } : {}),\n ...(reasoningContext ? { context: reasoningContext } : {}),\n };\n }\n\n // Configure response format\n if (schema) {\n responsesOptions.text = {\n format: buildJsonSchemaFormat(schema, schemaName, schemaDescription, schemaStrict),\n };\n } else if (responseFormat === 'json') {\n responsesOptions.text = { format: { type: 'json_object' } };\n } else if (typeof responseFormat === 'object' && responseFormat.type === 'json_schema') {\n responsesOptions.text = { format: responseFormat };\n }\n\n // Configure built-in tools\n if (useCodeInterpreter) {\n responsesOptions.tools = [{ type: 'code_interpreter', container: { type: 'auto' } }];\n responsesOptions.include = ['code_interpreter_call.outputs'];\n }\n\n if (useWebSearch) {\n responsesOptions.tools = [{ type: 'web_search_preview' }];\n }\n\n return await makeResponsesAPICall<T>(processedInput, responsesOptions);\n}\n", "// llm-openai-config.ts\nimport type { ImageGenerateParams } from 'openai/resources/images';\nimport type { OpenAIImageModel, OpenAIModel } from './types/llm-types';\n\nexport const DEFAULT_MODEL: OpenAIModel = 'gpt-5.6-luna';\n\nexport const DEFAULT_DEVELOPER_PROMPT = `\n You are a highly experienced coding, business analyst, and financial analyst associate.\n Help with coding, business process design and analysis, data generation and refinement, content creation, financial analysis, and more.\n When presented with a coding problem, logic problem, or other problem benefiting from systematic thinking, think through it step by step before giving your final answer.\n Present complete, high-confidence, final answers only. Do not rephrase to be more brief or omit parts of answers.\n Respond only with final content (e.g. code, a json or yaml object, a formatted string, or a markdown document) and nothing else. Do not reply with a preamble, introduction, or conclusion.\n`;\n\ninterface AIModelCosts {\n [modelName: string]: {\n inputCost: number;\n outputCost: number;\n cacheHitCost?: number;\n cacheWriteCost?: number;\n };\n}\n\nconst GPT_5_HIGH_CONTEXT_THRESHOLD_TOKENS = 272_000;\nconst GPT_5_HIGH_CONTEXT_INPUT_MULTIPLIER = 2;\nconst GPT_5_HIGH_CONTEXT_OUTPUT_MULTIPLIER = 1.5;\n\n/** Token costs in USD per 1M tokens. Last updated July 2026 from the OpenAI API pricing page. */\nexport const openAiModelCosts: AIModelCosts = {\n 'gpt-5.6': {\n inputCost: 5 / 1_000_000,\n cacheHitCost: 0.5 / 1_000_000,\n cacheWriteCost: 6.25 / 1_000_000,\n outputCost: 30 / 1_000_000,\n },\n 'gpt-5.6-sol': {\n inputCost: 5 / 1_000_000,\n cacheHitCost: 0.5 / 1_000_000,\n cacheWriteCost: 6.25 / 1_000_000,\n outputCost: 30 / 1_000_000,\n },\n 'gpt-5.6-terra': {\n inputCost: 2.5 / 1_000_000,\n cacheHitCost: 0.25 / 1_000_000,\n cacheWriteCost: 3.125 / 1_000_000,\n outputCost: 15 / 1_000_000,\n },\n 'gpt-5.6-luna': {\n inputCost: 1 / 1_000_000,\n cacheHitCost: 0.1 / 1_000_000,\n cacheWriteCost: 1.25 / 1_000_000,\n outputCost: 6 / 1_000_000,\n },\n 'gpt-5': {\n inputCost: 1.25 / 1_000_000,\n cacheHitCost: 0.125 / 1_000_000,\n outputCost: 10 / 1_000_000,\n },\n 'gpt-5-mini': {\n inputCost: 0.25 / 1_000_000,\n cacheHitCost: 0.025 / 1_000_000,\n outputCost: 2 / 1_000_000,\n },\n 'gpt-5.4-mini': {\n inputCost: 0.75 / 1_000_000,\n cacheHitCost: 0.075 / 1_000_000,\n outputCost: 4.5 / 1_000_000,\n },\n 'gpt-5.4-nano': {\n inputCost: 0.2 / 1_000_000,\n cacheHitCost: 0.02 / 1_000_000,\n outputCost: 1.25 / 1_000_000,\n },\n 'gpt-5-nano': {\n inputCost: 0.05 / 1_000_000,\n cacheHitCost: 0.005 / 1_000_000,\n outputCost: 0.4 / 1_000_000,\n },\n 'gpt-5.1': {\n inputCost: 1.25 / 1_000_000,\n cacheHitCost: 0.125 / 1_000_000,\n outputCost: 10 / 1_000_000,\n },\n 'gpt-5.4': {\n inputCost: 2.5 / 1_000_000,\n cacheHitCost: 0.25 / 1_000_000,\n outputCost: 15 / 1_000_000,\n },\n 'gpt-5.5': {\n inputCost: 5 / 1_000_000,\n cacheHitCost: 0.5 / 1_000_000,\n outputCost: 30 / 1_000_000,\n },\n 'gpt-5.5-pro': {\n inputCost: 30 / 1_000_000,\n outputCost: 180 / 1_000_000,\n },\n 'gpt-5.2': {\n inputCost: 1.75 / 1_000_000,\n cacheHitCost: 0.175 / 1_000_000,\n outputCost: 14 / 1_000_000,\n },\n 'gpt-5.2-pro': {\n inputCost: 21 / 1_000_000,\n outputCost: 168 / 1_000_000,\n },\n 'gpt-5.1-codex': {\n inputCost: 1.25 / 1_000_000,\n cacheHitCost: 0.125 / 1_000_000,\n outputCost: 10 / 1_000_000,\n },\n 'gpt-5.1-codex-max': {\n inputCost: 1.25 / 1_000_000,\n cacheHitCost: 0.125 / 1_000_000,\n outputCost: 10 / 1_000_000,\n },\n};\n\nexport const deepseekModelCosts: AIModelCosts = {\n 'deepseek-chat': {\n inputCost: 0.27 / 1_000_000, // $0.27 per 1M tokens (Cache miss price)\n cacheHitCost: 0.07 / 1_000_000, // $0.07 per 1M tokens (Cache hit price)\n outputCost: 1.1 / 1_000_000, // $1.10 per 1M tokens\n },\n 'deepseek-reasoner': {\n inputCost: 0.55 / 1_000_000, // $0.55 per 1M tokens (Cache miss price)\n cacheHitCost: 0.14 / 1_000_000, // $0.14 per 1M tokens (Cache hit price)\n outputCost: 2.19 / 1_000_000, // $2.19 per 1M tokens\n },\n};\n\nfunction shouldUseGPT5HighContextPricing(model: string, inputTokens: number): boolean {\n return (\n (model === 'gpt-5.4' || model === 'gpt-5.5' || model === 'gpt-5.6' || model === 'gpt-5.6-sol' || model === 'gpt-5.6-terra' || model === 'gpt-5.6-luna') &&\n inputTokens > GPT_5_HIGH_CONTEXT_THRESHOLD_TOKENS\n );\n}\n\nexport type PricedOpenAIImageModel =\n | 'gpt-image-2'\n | 'gpt-image-2-2026-04-21'\n | 'gpt-image-1.5'\n | 'gpt-image-1'\n | 'gpt-image-1-mini';\nexport type OpenAIImagePricingQuality = 'low' | 'medium' | 'high';\nexport type OpenAIImagePricingSize = '1024x1024' | '1024x1536' | '1536x1024';\n\nexport const DEFAULT_IMAGE_PRICING_QUALITY: OpenAIImagePricingQuality = 'high';\nexport const DEFAULT_IMAGE_PRICING_SIZE: OpenAIImagePricingSize = '1024x1024';\n\nconst PRICED_OPENAI_IMAGE_MODELS: readonly PricedOpenAIImageModel[] = [\n 'gpt-image-2',\n 'gpt-image-2-2026-04-21',\n 'gpt-image-1.5',\n 'gpt-image-1',\n 'gpt-image-1-mini',\n];\nconst OPENAI_IMAGE_PRICING_SIZES: readonly OpenAIImagePricingSize[] = ['1024x1024', '1024x1536', '1536x1024'];\n\n/**\n * Estimated image output costs in USD per image for common GPT Image sizes.\n * Last updated May 2026 from the OpenAI image generation guide. Text and image\n * input token costs for prompts and edit inputs are not included.\n */\nexport const openAiImageCostByQualityAndSize: Record<\n PricedOpenAIImageModel,\n Record<OpenAIImagePricingQuality, Record<OpenAIImagePricingSize, number>>\n> = {\n 'gpt-image-2': {\n low: {\n '1024x1024': 0.006,\n '1024x1536': 0.005,\n '1536x1024': 0.005,\n },\n medium: {\n '1024x1024': 0.053,\n '1024x1536': 0.041,\n '1536x1024': 0.041,\n },\n high: {\n '1024x1024': 0.211,\n '1024x1536': 0.165,\n '1536x1024': 0.165,\n },\n },\n 'gpt-image-2-2026-04-21': {\n low: {\n '1024x1024': 0.006,\n '1024x1536': 0.005,\n '1536x1024': 0.005,\n },\n medium: {\n '1024x1024': 0.053,\n '1024x1536': 0.041,\n '1536x1024': 0.041,\n },\n high: {\n '1024x1024': 0.211,\n '1024x1536': 0.165,\n '1536x1024': 0.165,\n },\n },\n 'gpt-image-1.5': {\n low: {\n '1024x1024': 0.009,\n '1024x1536': 0.013,\n '1536x1024': 0.013,\n },\n medium: {\n '1024x1024': 0.034,\n '1024x1536': 0.05,\n '1536x1024': 0.05,\n },\n high: {\n '1024x1024': 0.133,\n '1024x1536': 0.2,\n '1536x1024': 0.2,\n },\n },\n 'gpt-image-1': {\n low: {\n '1024x1024': 0.011,\n '1024x1536': 0.016,\n '1536x1024': 0.016,\n },\n medium: {\n '1024x1024': 0.042,\n '1024x1536': 0.063,\n '1536x1024': 0.063,\n },\n high: {\n '1024x1024': 0.167,\n '1024x1536': 0.25,\n '1536x1024': 0.25,\n },\n },\n 'gpt-image-1-mini': {\n low: {\n '1024x1024': 0.005,\n '1024x1536': 0.006,\n '1536x1024': 0.006,\n },\n medium: {\n '1024x1024': 0.011,\n '1024x1536': 0.015,\n '1536x1024': 0.015,\n },\n high: {\n '1024x1024': 0.036,\n '1024x1536': 0.052,\n '1536x1024': 0.052,\n },\n },\n};\n\n/** Default image output costs in USD per image for legacy callers. */\nexport const openAiImageCosts: Record<PricedOpenAIImageModel, number> = {\n 'gpt-image-2':\n openAiImageCostByQualityAndSize['gpt-image-2'][DEFAULT_IMAGE_PRICING_QUALITY][DEFAULT_IMAGE_PRICING_SIZE],\n 'gpt-image-2-2026-04-21':\n openAiImageCostByQualityAndSize['gpt-image-2-2026-04-21'][DEFAULT_IMAGE_PRICING_QUALITY][\n DEFAULT_IMAGE_PRICING_SIZE\n ],\n 'gpt-image-1.5':\n openAiImageCostByQualityAndSize['gpt-image-1.5'][DEFAULT_IMAGE_PRICING_QUALITY][DEFAULT_IMAGE_PRICING_SIZE],\n 'gpt-image-1':\n openAiImageCostByQualityAndSize['gpt-image-1'][DEFAULT_IMAGE_PRICING_QUALITY][DEFAULT_IMAGE_PRICING_SIZE],\n 'gpt-image-1-mini':\n openAiImageCostByQualityAndSize['gpt-image-1-mini'][DEFAULT_IMAGE_PRICING_QUALITY][DEFAULT_IMAGE_PRICING_SIZE],\n};\n\nfunction isPricedOpenAIImageModel(model: string): model is PricedOpenAIImageModel {\n return PRICED_OPENAI_IMAGE_MODELS.includes(model as PricedOpenAIImageModel);\n}\n\nfunction isOpenAIImagePricingSize(size: string): size is OpenAIImagePricingSize {\n return OPENAI_IMAGE_PRICING_SIZES.includes(size as OpenAIImagePricingSize);\n}\n\nfunction resolveImagePricingQuality(quality?: ImageGenerateParams['quality']): OpenAIImagePricingQuality {\n if (quality === 'low' || quality === 'medium' || quality === 'high') {\n return quality;\n }\n\n return DEFAULT_IMAGE_PRICING_QUALITY;\n}\n\nfunction resolveImagePricingSize(size?: ImageGenerateParams['size']): OpenAIImagePricingSize {\n if (typeof size === 'string' && isOpenAIImagePricingSize(size)) {\n return size;\n }\n\n return DEFAULT_IMAGE_PRICING_SIZE;\n}\n\n/**\n * Calculates the cost of generating images using OpenAI's Images API.\n *\n * @param model The image generation model name.\n * @param imageCount The number of images generated.\n * @param quality The requested image quality.\n * @param size The requested image size.\n * @returns The cost of generating the images in USD.\n */\nexport function calculateImageCost(\n model: OpenAIImageModel | string,\n imageCount: number,\n quality?: ImageGenerateParams['quality'],\n size?: ImageGenerateParams['size']\n): number {\n if (typeof model !== 'string' || typeof imageCount !== 'number' || imageCount <= 0) {\n return 0;\n }\n\n if (!isPricedOpenAIImageModel(model)) return 0;\n\n const pricingQuality = resolveImagePricingQuality(quality);\n const pricingSize = resolveImagePricingSize(size);\n const costPerImage = openAiImageCostByQualityAndSize[model][pricingQuality][pricingSize];\n\n return imageCount * costPerImage;\n}\n\n/**\n * Calculates the cost of calling a language model in USD based on the provider and model, tokens, and given costs per 1M tokens.\n *\n * @param provider The provider of the language model. Supported providers are 'openai' and 'deepseek'.\n * @param model The name of the language model. Supported models are listed in the `openAiModelCosts` and `deepseekModelCosts` objects.\n * @param inputTokens The number of input tokens passed to the language model.\n * @param outputTokens The number of output tokens generated by the language model.\n * @param reasoningTokens The number of output tokens generated by the language model for reasoning.\n * @param cacheHitTokens The number of input tokens billed at cached-input rates.\n * @param cacheWriteTokens The number of input tokens billed at cache-write rates.\n * @returns The cost of calling the language model in USD.\n */\nexport function calculateCost(\n provider: string,\n model: string,\n inputTokens: number,\n outputTokens: number,\n reasoningTokens?: number,\n cacheHitTokens?: number,\n cacheWriteTokens?: number\n): number {\n if (\n typeof provider !== 'string' ||\n typeof model !== 'string' ||\n typeof inputTokens !== 'number' ||\n typeof outputTokens !== 'number' ||\n (reasoningTokens !== undefined && typeof reasoningTokens !== 'number') ||\n (cacheHitTokens !== undefined && typeof cacheHitTokens !== 'number') ||\n (cacheWriteTokens !== undefined && typeof cacheWriteTokens !== 'number')\n ) {\n return 0;\n }\n\n const modelCosts = provider === 'deepseek' ? deepseekModelCosts[model] : openAiModelCosts[model];\n\n if (!modelCosts) return 0;\n\n const boundedCacheHitTokens = Math.min(Math.max(cacheHitTokens || 0, 0), inputTokens);\n const boundedCacheWriteTokens = Math.min(Math.max(cacheWriteTokens || 0, 0), inputTokens - boundedCacheHitTokens);\n const uncachedInputTokens = inputTokens - boundedCacheHitTokens - boundedCacheWriteTokens;\n const inputCost =\n uncachedInputTokens * modelCosts.inputCost +\n boundedCacheHitTokens * (modelCosts.cacheHitCost || modelCosts.inputCost) +\n boundedCacheWriteTokens * (modelCosts.cacheWriteCost || modelCosts.inputCost);\n\n let outputCost = outputTokens * modelCosts.outputCost;\n let reasoningCost = (reasoningTokens || 0) * modelCosts.outputCost;\n\n if (provider === 'openai' && shouldUseGPT5HighContextPricing(model, inputTokens)) {\n return (\n inputCost * GPT_5_HIGH_CONTEXT_INPUT_MULTIPLIER +\n outputCost * GPT_5_HIGH_CONTEXT_OUTPUT_MULTIPLIER +\n reasoningCost * GPT_5_HIGH_CONTEXT_OUTPUT_MULTIPLIER\n );\n }\n\n return inputCost + outputCost + reasoningCost;\n}\n", "import OpenAI from 'openai';\nimport { DEFAULT_MODEL } from './llm-config';\n/**\n * Fix a broken JSON string by attempting to extract and parse valid JSON content. This function is very lenient and will attempt to fix many types of JSON errors, including unbalanced brackets, missing or extra commas, improperly escaped $ signs, unquoted strings, trailing commas, missing closing brackets or braces, etc.\n * @param {string} jsonStr - The broken JSON string to fix\n * @returns {JsonValue} - The parsed JSON value\n */\nexport function fixBrokenJson(jsonStr: string): JsonValue {\n // Pre-process: Fix improperly escaped $ signs\n jsonStr = jsonStr.replace(/\\\\\\$/g, '$');\n\n let index = 0;\n\n function parse(): JsonValue {\n const results: JsonValue[] = [];\n while (index < jsonStr.length) {\n skipWhitespace();\n const value = parseValue();\n if (value !== undefined) {\n results.push(value);\n } else {\n index++; // Skip invalid character\n }\n }\n return results.length === 1 ? results[0] : results;\n }\n\n function parseValue(): JsonValue | undefined {\n skipWhitespace();\n const char = getChar();\n if (!char) return undefined;\n if (char === '{') return parseObject();\n if (char === '[') return parseArray();\n if (char === '\"' || char === \"'\") return parseString();\n if (char === 't' && jsonStr.slice(index, index + 4).toLowerCase() === 'true') {\n index += 4;\n return true;\n }\n if (char === 'f' && jsonStr.slice(index, index + 5).toLowerCase() === 'false') {\n index += 5;\n return false;\n }\n if (char === 'n' && jsonStr.slice(index, index + 4).toLowerCase() === 'null') {\n index += 4;\n return null;\n }\n if (/[a-zA-Z]/.test(char)) return parseString(); // Unquoted string\n if (char === '-' || char === '.' || /\\d/.test(char)) return parseNumber();\n return undefined; // Unknown character\n }\n\n function parseObject(): JsonObject {\n const obj: JsonObject = {};\n index++; // Skip opening brace\n skipWhitespace();\n while (index < jsonStr.length && getChar() !== '}') {\n skipWhitespace();\n const key = parseString();\n if (key === undefined) {\n console.warn(`Expected key at position ${index}`);\n index++;\n continue;\n }\n skipWhitespace();\n if (getChar() === ':') {\n index++; // Skip colon\n } else {\n console.warn(`Missing colon after key \"${key}\" at position ${index}`);\n }\n skipWhitespace();\n const value = parseValue();\n if (value === undefined) {\n console.warn(`Expected value for key \"${key}\" at position ${index}`);\n index++;\n continue;\n }\n obj[key] = value;\n skipWhitespace();\n if (getChar() === ',') {\n index++; // Skip comma\n } else {\n break;\n }\n skipWhitespace();\n }\n if (getChar() === '}') {\n index++; // Skip closing brace\n } else {\n // Add a closing brace if it's missing\n jsonStr += '}';\n }\n return obj;\n }\n\n function parseArray(): JsonArray {\n const arr: JsonArray = [];\n index++; // Skip opening bracket\n skipWhitespace();\n while (index < jsonStr.length && getChar() !== ']') {\n const value = parseValue();\n if (value === undefined) {\n console.warn(`Expected value at position ${index}`);\n index++;\n } else {\n arr.push(value);\n }\n skipWhitespace();\n if (getChar() === ',') {\n index++; // Skip comma\n } else {\n break;\n }\n skipWhitespace();\n }\n if (getChar() === ']') {\n index++; // Skip closing bracket\n } else {\n console.warn(`Missing closing bracket for array at position ${index}`);\n }\n return arr;\n }\n\n function parseString(): string {\n const startChar = getChar();\n let result = '';\n let isQuoted = false;\n let delimiter = '';\n\n if (startChar === '\"' || startChar === \"'\") {\n isQuoted = true;\n delimiter = startChar;\n index++; // Skip opening quote\n }\n\n while (index < jsonStr.length) {\n const char = getChar();\n if (isQuoted) {\n if (char === delimiter) {\n index++; // Skip closing quote\n return result;\n } else if (char === '\\\\') {\n index++;\n const escapeChar = getChar();\n const escapeSequences: { [key: string]: string } = {\n n: '\\n',\n r: '\\r',\n t: '\\t',\n b: '\\b',\n f: '\\f',\n '\\\\': '\\\\',\n '/': '/',\n '\"': '\"',\n \"'\": \"'\",\n $: '$',\n };\n result += escapeSequences[escapeChar] || escapeChar;\n } else {\n result += char;\n }\n index++;\n } else {\n if (/\\s|,|}|]|\\:/.test(char)) {\n return result;\n } else {\n result += char;\n index++;\n }\n }\n }\n if (isQuoted) {\n console.warn(`Missing closing quote for string starting at position ${index}`);\n }\n return result;\n }\n\n function parseNumber(): number | undefined {\n const numberRegex = /^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?/;\n const match = numberRegex.exec(jsonStr.slice(index));\n if (match) {\n index += match[0].length;\n return parseFloat(match[0]);\n } else {\n console.warn(`Invalid number at position ${index}`);\n index++;\n return undefined;\n }\n }\n\n function getChar(): string {\n return jsonStr[index];\n }\n\n function skipWhitespace(): void {\n while (/\\s/.test(getChar())) index++;\n }\n\n try {\n return parse();\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n console.error(`Error parsing JSON at position ${index}: ${msg}`);\n return null;\n }\n}\n\n/**\n * Returns true if the given JSON string is valid, false otherwise.\n *\n * This function simply attempts to parse the given string as JSON and returns true if successful, or false if an error is thrown.\n *\n * @param {string} jsonString The JSON string to validate.\n * @returns {boolean} True if the JSON string is valid, false otherwise.\n */\nexport function isValidJson(jsonString: string): boolean {\n try {\n JSON.parse(jsonString);\n return true;\n } catch {\n return false;\n }\n}\n\n// Types just for fixing JSON with AI\ninterface JsonObject {\n [key: string]: JsonValue;\n}\ntype JsonArray = JsonValue[];\ntype JsonValue = string | number | boolean | null | JsonObject | JsonArray;\n\nlet openai: OpenAI;\n\n/**\n * Initializes an instance of the OpenAI client, using the provided API key or the value of the OPENAI_API_KEY environment variable if no key is provided.\n * @param apiKey - the API key to use, or undefined to use the value of the OPENAI_API_KEY environment variable\n * @returns an instance of the OpenAI client\n * @throws an error if the API key is not provided and the OPENAI_API_KEY environment variable is not set\n */\nfunction initializeOpenAI(apiKey?: string): OpenAI {\n const key = apiKey || process.env.OPENAI_API_KEY;\n if (!key) {\n throw new Error('OpenAI API key is not provided and OPENAI_API_KEY environment variable is not set');\n }\n return new OpenAI({\n apiKey: key,\n defaultHeaders: { 'User-Agent': 'My Server-side Application (compatible; OpenAI API Client)' },\n });\n}\n\n/**\n * Fixes broken JSON by sending it to OpenAI to fix it.\n * If the model fails to return valid JSON, an error is thrown.\n * @param jsonStr - the broken JSON to fix\n * @param apiKey - the OpenAI API key to use, or undefined to use the value of the OPENAI_API_KEY environment variable\n * @returns the fixed JSON\n * @throws an error if the model fails to return valid JSON\n */\nexport async function fixJsonWithAI(jsonStr: string, apiKey?: string): Promise<JsonValue> {\n try {\n if (!openai) {\n openai = initializeOpenAI();\n }\n\n const completion = await openai.chat.completions.create({\n model: DEFAULT_MODEL,\n messages: [\n {\n role: 'system',\n content: 'You are a JSON fixer. Return only valid JSON without any additional text or explanation.',\n },\n {\n role: 'user',\n content: `Fix this broken JSON:\\n${jsonStr}`,\n },\n ],\n response_format: { type: 'json_object' },\n });\n\n const fixedJson = completion.choices[0]?.message?.content;\n\n if (fixedJson && isValidJson(fixedJson)) {\n return JSON.parse(fixedJson);\n }\n throw new Error('Failed to fix JSON with AI');\n } catch (err: unknown) {\n const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';\n throw new Error(`Error fixing JSON with AI: ${errorMessage}`);\n }\n}\n", "// llm-utils.ts\n\nimport { LLMModel, OpenAIModel, OpenAIResponseFormat } from './types';\nimport { fixBrokenJson, fixJsonWithAI } from './json-tools';\n\nexport function normalizeModelName(model: string): LLMModel {\n return model.replace(/_/g, '-').toLowerCase() as LLMModel;\n}\n\nexport const CODE_BLOCK_TYPES = ['javascript', 'js', 'graphql', 'json', 'typescript', 'python', 'markdown', 'yaml'];\n\n /**\n * Tries to parse JSON from the given content string according to the specified\n * response format. If the response format is 'json' or a JSON schema object, it\n * will attempt to parse the content using multiple strategies. If any of the\n * strategies succeed, it will return the parsed JSON object. If all of them fail,\n * it will throw an error.\n *\n * @param content The content string to parse\n * @param responseFormat The desired format of the response\n * @returns The parsed JSON object or null if it fails\n */\nexport async function parseResponse<T>(content: string, responseFormat: OpenAIResponseFormat): Promise<T | null> {\n if (!content) return null;\n\n if (responseFormat === 'json' || (typeof responseFormat === 'object' && responseFormat?.type === 'json_schema')) {\n let cleanedContent = content.trim();\n let detectedType: string | null = null;\n\n // Remove code block markers if present\n const startsWithCodeBlock = CODE_BLOCK_TYPES.some((type) => {\n if (cleanedContent.startsWith(`\\`\\`\\`${type}`)) {\n detectedType = type;\n return true;\n }\n return false;\n });\n\n if (startsWithCodeBlock && cleanedContent.endsWith('```')) {\n const firstLineEndIndex = cleanedContent.indexOf('\\n');\n if (firstLineEndIndex !== -1) {\n cleanedContent = cleanedContent.slice(firstLineEndIndex + 1, -3).trim();\n console.log(`Code block for type ${detectedType} detected and removed. Cleaned content: ${cleanedContent}`);\n }\n }\n\n // Multiple JSON parsing strategies\n const jsonParsingStrategies = [\n // Strategy 1: Direct parsing\n () => {\n try {\n return JSON.parse(cleanedContent);\n } catch {\n return null;\n }\n },\n // Strategy 2: Extract JSON from between first {} or []\n () => {\n const jsonMatch = cleanedContent.match(/[\\{\\[].*[\\}\\]]/s);\n if (jsonMatch) {\n try {\n return JSON.parse(jsonMatch[0]);\n } catch {\n return null;\n }\n }\n return null;\n },\n // Strategy 3: Remove leading/trailing text and try parsing\n () => {\n const jsonMatch = cleanedContent.replace(/^[^{[]*|[^}\\]]*$/g, '');\n try {\n return JSON.parse(jsonMatch);\n } catch {\n return null;\n }\n },\n // Strategy 4: Use fixJsonWithAI\n () => {\n return fixJsonWithAI(cleanedContent);\n },\n // Strategy 5: Use fixBrokenJson\n () => {\n return fixBrokenJson(cleanedContent);\n },\n ];\n\n // Try each parsing strategy\n for (const strategy of jsonParsingStrategies) {\n const result = await strategy();\n if (result !== null) {\n return result as T;\n }\n }\n\n // If all strategies fail, throw an error\n console.error(`Failed to parse JSON from content: ${cleanedContent}. Original JSON: ${content}`);\n throw new Error('Unable to parse JSON response');\n } else {\n return content as T;\n }\n}\n", "import OpenAI from 'openai';\nimport { ImageGenerationOptions, LLMModel, DiscoImageModel, OPENAI_MODELS } from './types';\nimport { calculateImageCost } from './llm-config';\nimport { ImageGenerateParams, ImagesResponse } from 'openai/resources/images';\n\n/**\n * Enhanced ImagesResponse that includes cost calculation\n */\nexport interface ImageResponseWithUsage extends ImagesResponse {\n usage?: ImagesResponse['usage'] & {\n provider: string;\n model: DiscoImageModel;\n cost: number;\n visionModel?: LLMModel;\n };\n}\n\nexport const DEFAULT_IMAGE_MODEL: DiscoImageModel = 'gpt-image-2';\n\nexport const resolveImageModel = (model?: DiscoImageModel): DiscoImageModel => model ?? DEFAULT_IMAGE_MODEL;\n\nconst MULTIMODAL_VISION_MODELS: ReadonlySet<LLMModel> = new Set(OPENAI_MODELS);\n\n/**\n * Makes a call to the OpenAI Images API to generate images based on a text prompt.\n *\n * This function provides access to OpenAI's image generation capabilities with support for:\n * - Different output formats (JPEG, PNG, WebP)\n * - Various image sizes and quality settings\n * - Multiple image generation in a single call\n * - Base64 encoded image data return\n *\n * @example\n * // Basic image generation\n * const response = await makeImagesCall('A beautiful sunset over mountains');\n *\n * @example\n * // Custom options\n * const response = await makeImagesCall('A birthday cake', {\n * size: '1024x1024',\n * outputFormat: 'png',\n * quality: 'high',\n * count: 2\n * });\n *\n * @param prompt - The text prompt describing the image to generate\n * @param options - Configuration options for image generation. Includes:\n * - size: Image dimensions (uses OpenAI's size options)\n * - outputFormat: Image format ('jpeg', 'png', 'webp') - defaults to 'webp'\n * - compression: Compression level (number) - defaults to 50\n * - quality: Quality setting (uses OpenAI's quality options) - defaults to 'high'\n * - count: Number of images to generate - defaults to 1\n * - background: Background setting for transparency support\n * - moderation: Content moderation level\n * - apiKey: OpenAI API key (optional, falls back to environment variable)\n * @returns Promise<ImageResponseWithUsage> - The image generation response with cost information\n * @throws Error if the API call fails or invalid parameters are provided\n */\nexport async function makeImagesCall(\n prompt: string,\n options: ImageGenerationOptions = {}\n): Promise<ImageResponseWithUsage> {\n const {\n model,\n size = 'auto',\n outputFormat = 'webp',\n compression = 50,\n quality = 'high',\n count = 1,\n background = 'auto',\n moderation = 'auto',\n apiKey,\n visionModel,\n } = options;\n const imageModel = resolveImageModel(model);\n const supportedVisionModel = visionModel && MULTIMODAL_VISION_MODELS.has(visionModel) ? visionModel : undefined;\n if (visionModel && !supportedVisionModel) {\n console.warn(\n `Vision model ${visionModel} is not recognized as a multimodal OpenAI model. Ignoring for image usage metadata.`\n );\n }\n\n // Get API key\n const effectiveApiKey = apiKey || process.env.OPENAI_API_KEY;\n if (!effectiveApiKey) {\n throw new Error('OpenAI API key is not provided and OPENAI_API_KEY environment variable is not set');\n }\n\n // Validate inputs\n if (!prompt || typeof prompt !== 'string') {\n throw new Error('Prompt must be a non-empty string');\n }\n\n if (count && (count < 1 || count > 10)) {\n throw new Error('Count must be between 1 and 10');\n }\n\n if (compression && (compression < 0 || compression > 100)) {\n throw new Error('Compression must be between 0 and 100');\n }\n\n const openai = new OpenAI({\n apiKey: effectiveApiKey,\n });\n\n // Build the request parameters using OpenAI's type\n const requestParams: ImageGenerateParams = {\n model: imageModel,\n prompt,\n n: count || 1,\n size: size || 'auto',\n quality: quality || 'auto',\n background: background || 'auto',\n moderation: moderation || 'auto',\n };\n\n // Add output format if specified\n if (outputFormat) {\n requestParams.output_format = outputFormat;\n }\n\n // Add compression if specified\n if (compression !== undefined) {\n requestParams.output_compression = compression;\n }\n\n try {\n // Make the API call\n const response = await openai.images.generate(requestParams);\n\n // Validate response\n if (!response.data || response.data.length === 0) {\n throw new Error('No images returned from OpenAI Images API');\n }\n\n // Calculate cost\n const cost = calculateImageCost(imageModel, count || 1, quality, size);\n\n // Return the response with enhanced usage information\n const enhancedResponse: ImageResponseWithUsage = {\n ...response,\n usage: {\n // OpenAI Images response may not include usage details per image; preserve if present\n ...(response.usage ?? {\n input_tokens: 0,\n input_tokens_details: { image_tokens: 0, text_tokens: 0 },\n output_tokens: 0,\n total_tokens: 0,\n }),\n provider: 'openai',\n model: imageModel,\n cost,\n ...(supportedVisionModel ? { visionModel: supportedVisionModel } : {}),\n },\n };\n\n return enhancedResponse;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n throw new Error(`OpenAI Images API call failed: ${message}`);\n }\n} \n", "import OpenAI from 'openai';\nimport {\n ChatCompletionContentPart,\n ChatCompletionMessageParam,\n ChatCompletionCreateParams,\n} from 'openai/resources/chat';\n\nimport { calculateCost } from './llm-config';\nimport { parseResponse, normalizeModelName } from './llm-utils';\nimport { LLMResponse, LLMOptions, OpenAIModel, OpenAIResponseFormat, DeepseekModel, LLMModel } from './types';\n\n/**\n * Default options for Deepseek API calls\n */\nconst DEFAULT_DEEPSEEK_OPTIONS = {\n defaultModel: 'deepseek-chat' as DeepseekModel,\n};\n\n/**\n * Checks if the given model is a supported Deepseek model\n * @param model The model to check\n * @returns True if the model is supported, false otherwise\n */\nconst isSupportedDeepseekModel = (model: string): model is DeepseekModel => {\n return ['deepseek-chat', 'deepseek-reasoner'].includes(model);\n};\n\n/**\n * Checks if the given Deepseek model supports JSON output format\n * @param model The model to check\n * @returns True if JSON output is supported, false otherwise\n */\nconst supportsJsonOutput = (model: string): boolean => {\n return model === 'deepseek-chat';\n};\n\n/**\n * Checks if the given Deepseek model supports tool calling\n * @param model The model to check\n * @returns True if tool calling is supported, false otherwise\n */\nconst supportsToolCalling = (model: string): boolean => {\n return model === 'deepseek-chat';\n};\n\n/**\n * Gets the appropriate response format option for Deepseek API\n * \n * @param responseFormat The desired response format\n * @param model The model being used\n * @returns Object representing the Deepseek response format option\n */\nfunction getDeepseekResponseFormatOption(responseFormat: OpenAIResponseFormat, model: string): { type: 'text' } | { type: 'json_object' } {\n // Check if the model supports JSON output\n if (responseFormat !== 'text' && !supportsJsonOutput(model)) {\n console.warn(`Model ${model} does not support JSON output. Using text format instead.`);\n return { type: 'text' };\n }\n\n if (responseFormat === 'text') {\n return { type: 'text' };\n }\n if (responseFormat === 'json' || (typeof responseFormat === 'object' && responseFormat.type === 'json_schema')) {\n return { type: 'json_object' };\n }\n return { type: 'text' };\n}\n\n/**\n * Creates a completion using the Deepseek API\n * \n * @param content The content to pass to the API\n * @param responseFormat The desired format of the response\n * @param options Additional options for the API call\n * @returns Promise resolving to the API response\n */\nasync function createDeepseekCompletion(\n content: string | ChatCompletionContentPart[],\n responseFormat: OpenAIResponseFormat,\n options: LLMOptions = {}\n) {\n // Extract the model or use default\n const modelOption = options.model || DEFAULT_DEEPSEEK_OPTIONS.defaultModel;\n const normalizedModel = normalizeModelName(modelOption);\n \n // Validate model\n if (!isSupportedDeepseekModel(normalizedModel)) {\n throw new Error(`Unsupported Deepseek model: ${normalizedModel}. Please use 'deepseek-chat' or 'deepseek-reasoner'.`);\n }\n\n // Check if tools are requested with a model that doesn't support them\n if (options.tools && options.tools.length > 0 && !supportsToolCalling(normalizedModel)) {\n throw new Error(`Model ${normalizedModel} does not support tool calling.`);\n }\n\n const apiKey = options.apiKey || process.env.DEEPSEEK_API_KEY;\n if (!apiKey) {\n throw new Error('Deepseek API key is not provided and DEEPSEEK_API_KEY environment variable is not set');\n }\n\n // Initialize OpenAI client with Deepseek API URL\n const openai = new OpenAI({\n apiKey,\n baseURL: 'https://api.deepseek.com',\n });\n\n const messages: ChatCompletionMessageParam[] = [];\n\n // Add system message with developer prompt if present\n if (options.developerPrompt) {\n messages.push({\n role: 'system',\n content: options.developerPrompt,\n });\n }\n\n // Add context if present\n if (options.context) {\n messages.push(...options.context);\n }\n\n // Add user content\n if (typeof content === 'string') {\n messages.push({\n role: 'user',\n content,\n });\n } else {\n messages.push({\n role: 'user',\n content,\n });\n }\n\n // If JSON response format, include a hint in the system prompt\n if ((responseFormat === 'json' || (typeof responseFormat === 'object' && responseFormat.type === 'json_schema')) \n && supportsJsonOutput(normalizedModel)) {\n // If there's no system message yet, add one\n if (!messages.some(m => m.role === 'system')) {\n messages.unshift({\n role: 'system',\n content: 'Please respond in valid JSON format.',\n });\n } else {\n // Append to existing system message\n const systemMsgIndex = messages.findIndex(m => m.role === 'system');\n const systemMsg = messages[systemMsgIndex];\n if (typeof systemMsg.content === 'string') {\n messages[systemMsgIndex] = {\n ...systemMsg,\n content: `${systemMsg.content} Please respond in valid JSON format.`,\n };\n }\n }\n }\n\n const queryOptions: ChatCompletionCreateParams = {\n model: normalizedModel,\n messages,\n response_format: getDeepseekResponseFormatOption(responseFormat, normalizedModel),\n temperature: options.temperature,\n top_p: options.top_p,\n frequency_penalty: options.frequency_penalty,\n presence_penalty: options.presence_penalty,\n max_tokens: options.max_completion_tokens,\n };\n\n // Only add tools if the model supports them\n if (options.tools && supportsToolCalling(normalizedModel)) {\n queryOptions.tools = options.tools;\n }\n\n try {\n const completion = await openai.chat.completions.create(queryOptions);\n\n return {\n id: completion.id,\n content: completion.choices[0]?.message?.content || '',\n tool_calls: completion.choices[0]?.message?.tool_calls,\n usage: completion.usage || {\n prompt_tokens: 0,\n completion_tokens: 0,\n total_tokens: 0,\n },\n system_fingerprint: completion.system_fingerprint,\n provider: 'deepseek',\n model: normalizedModel as DeepseekModel,\n };\n } catch (error) {\n console.error('Error calling Deepseek API:', error);\n throw error;\n }\n}\n\n/**\n * Makes a call to the Deepseek AI API.\n *\n * @param content The content to pass to the LLM. Can be a string or an array of content parts.\n * @param responseFormat The format of the response. Defaults to 'json'.\n * @param options Configuration options including model ('deepseek-chat' or 'deepseek-reasoner'), tools, and apiKey.\n * @return A promise that resolves to the response from the Deepseek API.\n */\nexport const makeDeepseekCall = async <T = string>(\n content: string | ChatCompletionContentPart[],\n responseFormat: OpenAIResponseFormat = 'json',\n options: LLMOptions = {}\n): Promise<LLMResponse<T>> => {\n // Set default model if not provided\n const mergedOptions = {\n ...options,\n };\n\n if (!mergedOptions.model) {\n mergedOptions.model = DEFAULT_DEEPSEEK_OPTIONS.defaultModel;\n }\n\n const modelName = normalizeModelName(mergedOptions.model as string);\n \n // Check if the requested response format is compatible with the model\n if (responseFormat !== 'text' && !supportsJsonOutput(modelName)) {\n console.warn(`Model ${modelName} does not support JSON output. Will return error in the response.`);\n return {\n response: {\n error: `Model ${modelName} does not support JSON output format.`\n } as unknown as T,\n usage: {\n prompt_tokens: 0,\n completion_tokens: 0,\n reasoning_tokens: 0,\n provider: 'deepseek',\n model: modelName as DeepseekModel,\n cache_hit_tokens: 0,\n cost: 0,\n },\n tool_calls: undefined,\n };\n }\n\n // Check if tools are requested with a model that doesn't support them\n if (mergedOptions.tools && mergedOptions.tools.length > 0 && !supportsToolCalling(modelName)) {\n console.warn(`Model ${modelName} does not support tool calling. Will return error in the response.`);\n return {\n response: {\n error: `Model ${modelName} does not support tool calling.`\n } as unknown as T,\n usage: {\n prompt_tokens: 0,\n completion_tokens: 0,\n reasoning_tokens: 0,\n provider: 'deepseek',\n model: modelName as DeepseekModel,\n cache_hit_tokens: 0,\n cost: 0,\n },\n tool_calls: undefined,\n };\n }\n\n try {\n const completion = await createDeepseekCompletion(content, responseFormat, mergedOptions);\n\n // Handle tool calls similarly to OpenAI\n if (completion.tool_calls && completion.tool_calls.length > 0) {\n const fnCalls = completion.tool_calls\n .filter((tc) => tc.type === 'function')\n .map((tc) => ({\n id: tc.id,\n name: (tc as Extract<typeof tc, { type: 'function' }>).function.name,\n arguments: JSON.parse((tc as Extract<typeof tc, { type: 'function' }>).function.arguments),\n }));\n return {\n response: { tool_calls: fnCalls } as T,\n usage: {\n prompt_tokens: completion.usage.prompt_tokens,\n completion_tokens: completion.usage.completion_tokens,\n reasoning_tokens: 0, // Deepseek doesn't provide reasoning tokens separately\n provider: 'deepseek',\n model: completion.model,\n cache_hit_tokens: 0, // Not provided directly in API response\n cost: calculateCost(\n 'deepseek',\n completion.model,\n completion.usage.prompt_tokens,\n completion.usage.completion_tokens,\n 0,\n 0 // Cache hit tokens (not provided in the response)\n ),\n },\n tool_calls: completion.tool_calls,\n };\n }\n\n // Handle regular responses\n const parsedResponse = await parseResponse<T>(completion.content, responseFormat);\n if (parsedResponse === null) {\n throw new Error('Failed to parse Deepseek response');\n }\n\n return {\n response: parsedResponse,\n usage: {\n prompt_tokens: completion.usage.prompt_tokens,\n completion_tokens: completion.usage.completion_tokens,\n reasoning_tokens: 0, // Deepseek doesn't provide reasoning tokens separately\n provider: 'deepseek',\n model: completion.model,\n cache_hit_tokens: 0, // Not provided directly in API response\n cost: calculateCost(\n 'deepseek',\n completion.model,\n completion.usage.prompt_tokens,\n completion.usage.completion_tokens,\n 0,\n 0 // Cache hit tokens (not provided in the response)\n ),\n },\n tool_calls: completion.tool_calls,\n };\n } catch (error) {\n // If there's an error due to incompatible features, return a structured error\n console.error('Error in Deepseek API call:', error);\n return {\n response: {\n error: error instanceof Error ? error.message : 'Unknown error'\n } as unknown as T,\n usage: {\n prompt_tokens: 0,\n completion_tokens: 0,\n reasoning_tokens: 0,\n provider: 'deepseek',\n model: modelName as DeepseekModel,\n cache_hit_tokens: 0,\n cost: 0,\n },\n tool_calls: undefined,\n };\n }\n};\n", "import { log as baseLog } from './logging';\nimport { LogOptions } from './types/logging-types';\nimport {\n Period,\n IntradayReporting,\n PeriodDates,\n MarketTimeParams,\n OutputFormat,\n MarketOpenCloseResult,\n MarketStatus,\n MarketTimesConfig,\n TradingDaysBackOptions,\n} from './types/market-time-types';\nimport { marketHolidays, marketEarlyCloses } from './market-hours';\n\n// Constants for NY market times (Eastern Time)\nexport const MARKET_CONFIG = {\n TIMEZONE: 'America/New_York',\n UTC_OFFSET_STANDARD: -5, // EST\n UTC_OFFSET_DST: -4, // EDT\n TIMES: {\n EXTENDED_START: { hour: 4, minute: 0 },\n MARKET_OPEN: { hour: 9, minute: 30 },\n EARLY_MARKET_END: { hour: 10, minute: 0 },\n MARKET_CLOSE: { hour: 16, minute: 0 },\n EARLY_CLOSE: { hour: 13, minute: 0 },\n EXTENDED_END: { hour: 20, minute: 0 },\n EARLY_EXTENDED_END: { hour: 17, minute: 0 },\n },\n} as const;\n\nconst log = (message: string, options: LogOptions = { type: 'info' }) => {\n baseLog(message, { ...options, source: 'MarketTime' });\n};\n\n// Helper: Get NY offset for a given UTC date (DST rules for US)\n/**\n * Returns the NY timezone offset (in hours) for a given UTC date, accounting for US DST rules.\n * @param date - UTC date\n * @returns offset in hours (-5 for EST, -4 for EDT)\n */\nfunction getNYOffset(date: Date): number {\n // US DST starts 2nd Sunday in March, ends 1st Sunday in November\n const year = date.getUTCFullYear();\n const dstStart = getNthWeekdayOfMonth(year, 3, 0, 2); // March, Sunday, 2nd\n const dstEnd = getNthWeekdayOfMonth(year, 11, 0, 1); // November, Sunday, 1st\n const utcTime = date.getTime();\n\n if (utcTime >= dstStart.getTime() && utcTime < dstEnd.getTime()) {\n return MARKET_CONFIG.UTC_OFFSET_DST;\n }\n return MARKET_CONFIG.UTC_OFFSET_STANDARD;\n}\n\n// Helper: Get nth weekday of month in UTC\n/**\n * Returns the nth weekday of a given month in UTC.\n * @param year - Year\n * @param month - 1-based month (e.g. March = 3)\n * @param weekday - 0=Sunday, 1=Monday, ...\n * @param n - nth occurrence\n * @returns Date object for the nth weekday\n */\nfunction getNthWeekdayOfMonth(year: number, month: number, weekday: number, n: number): Date {\n // month: 1-based (March = 3), weekday: 0=Sunday\n const firstDay = new Date(Date.UTC(year, month - 1, 1));\n let count = 0;\n for (let d = 1; d <= 31; d++) {\n const date = new Date(Date.UTC(year, month - 1, d));\n if (date.getUTCMonth() !== month - 1) break;\n if (date.getUTCDay() === weekday) {\n count++;\n if (count === n) return date;\n }\n }\n // fallback: last day of month\n return new Date(Date.UTC(year, month - 1, 28));\n}\n\n// Helper: Convert UTC date to NY time (returns new Date object)\n/**\n * Converts a UTC date to NY time (returns a new Date object).\n * @param date - UTC date\n * @returns Date object in NY time\n */\nfunction toNYTime(date: Date): Date {\n const offset = getNYOffset(date);\n // NY offset in hours\n const utcMillis = date.getTime();\n const nyMillis = utcMillis + offset * 60 * 60 * 1000;\n return new Date(nyMillis);\n}\n\n// Helper: Convert NY time to UTC (returns new Date object)\n/**\n * Converts a NY time date to UTC (returns a new Date object).\n * @param date - NY time date\n * @returns Date object in UTC\n */\nfunction fromNYTime(date: Date): Date {\n const offset = getNYOffset(date);\n const nyMillis = date.getTime();\n const utcMillis = nyMillis - offset * 60 * 60 * 1000;\n return new Date(utcMillis);\n}\n\n// Helper: Format date in ISO, unix, etc.\n/**\n * Formats a date in ISO, unix-seconds, or unix-ms format.\n * @param date - Date object\n * @param outputFormat - Output format ('iso', 'unix-seconds', 'unix-ms')\n * @returns Formatted date string or number\n */\nfunction formatDate(date: Date, outputFormat: OutputFormat = 'iso'): string | number {\n switch (outputFormat) {\n case 'unix-seconds':\n return Math.floor(date.getTime() / 1000);\n case 'unix-ms':\n return date.getTime();\n case 'iso':\n default:\n return date.toISOString();\n }\n}\n\n// Helper: Format date in NY locale string\n/**\n * Formats a date in NY locale string.\n * @param date - Date object\n * @returns NY locale string\n */\nfunction formatNYLocale(date: Date): string {\n return date.toLocaleString('en-US', { timeZone: 'America/New_York' });\n}\n\n// Market calendar logic\n/**\n * Market calendar logic for holidays, weekends, and market days.\n */\nclass MarketCalendar {\n /**\n * Checks if a date is a weekend in NY time.\n * @param date - Date object\n * @returns true if weekend, false otherwise\n */\n isWeekend(date: Date): boolean {\n const day = toNYTime(date).getUTCDay();\n return day === 0 || day === 6;\n }\n\n /**\n * Checks if a date is a market holiday in NY time.\n * @param date - Date object\n * @returns true if holiday, false otherwise\n */\n isHoliday(date: Date): boolean {\n const nyDate = toNYTime(date);\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth() + 1;\n const day = nyDate.getUTCDate();\n const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;\n const yearHolidays = marketHolidays[year];\n if (!yearHolidays) return false;\n return Object.values(yearHolidays).some((holiday) => holiday.date === formattedDate);\n }\n\n /**\n * Checks if a date is an early close day in NY time.\n * @param date - Date object\n * @returns true if early close, false otherwise\n */\n isEarlyCloseDay(date: Date): boolean {\n const nyDate = toNYTime(date);\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth() + 1;\n const day = nyDate.getUTCDate();\n const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;\n const yearEarlyCloses = marketEarlyCloses[year];\n return yearEarlyCloses && yearEarlyCloses[formattedDate] !== undefined;\n }\n\n /**\n * Gets the early close time (in minutes from midnight) for a given date.\n * @param date - Date object\n * @returns minutes from midnight or null\n */\n getEarlyCloseTime(date: Date): number | null {\n const nyDate = toNYTime(date);\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth() + 1;\n const day = nyDate.getUTCDate();\n const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;\n const yearEarlyCloses = marketEarlyCloses[year];\n if (yearEarlyCloses && yearEarlyCloses[formattedDate]) {\n const [hours, minutes] = yearEarlyCloses[formattedDate].time.split(':').map(Number);\n return hours * 60 + minutes;\n }\n return null;\n }\n\n /**\n * Checks if a date is a market day (not weekend or holiday).\n * @param date - Date object\n * @returns true if market day, false otherwise\n */\n isMarketDay(date: Date): boolean {\n return !this.isWeekend(date) && !this.isHoliday(date);\n }\n\n /**\n * Gets the next market day after the given date.\n * @param date - Date object\n * @returns Date object for next market day\n */\n getNextMarketDay(date: Date): Date {\n let nextDay = new Date(date.getTime() + 24 * 60 * 60 * 1000);\n while (!this.isMarketDay(nextDay)) {\n nextDay = new Date(nextDay.getTime() + 24 * 60 * 60 * 1000);\n }\n return nextDay;\n }\n\n /**\n * Gets the previous market day before the given date.\n * @param date - Date object\n * @returns Date object for previous market day\n */\n getPreviousMarketDay(date: Date): Date {\n let prevDay = new Date(date.getTime() - 24 * 60 * 60 * 1000);\n while (!this.isMarketDay(prevDay)) {\n prevDay = new Date(prevDay.getTime() - 24 * 60 * 60 * 1000);\n }\n return prevDay;\n }\n}\n\n// Market open/close times\n/**\n * Returns market open/close times for a given date, including extended and early closes.\n * @param date - Date object\n * @returns MarketOpenCloseResult\n */\nfunction getMarketTimes(date: Date): MarketOpenCloseResult {\n const calendar = new MarketCalendar();\n const nyDate = toNYTime(date);\n if (!calendar.isMarketDay(date)) {\n return {\n marketOpen: false,\n open: null,\n close: null,\n openExt: null,\n closeExt: null,\n };\n }\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth();\n const day = nyDate.getUTCDate();\n\n // Helper to build NY time for a given hour/minute\n function buildNYTime(hour: number, minute: number): Date {\n const d = new Date(Date.UTC(year, month, day, hour, minute, 0, 0));\n return fromNYTime(d);\n }\n\n let open = buildNYTime(MARKET_CONFIG.TIMES.MARKET_OPEN.hour, MARKET_CONFIG.TIMES.MARKET_OPEN.minute);\n let close = buildNYTime(MARKET_CONFIG.TIMES.MARKET_CLOSE.hour, MARKET_CONFIG.TIMES.MARKET_CLOSE.minute);\n let openExt = buildNYTime(MARKET_CONFIG.TIMES.EXTENDED_START.hour, MARKET_CONFIG.TIMES.EXTENDED_START.minute);\n let closeExt = buildNYTime(MARKET_CONFIG.TIMES.EXTENDED_END.hour, MARKET_CONFIG.TIMES.EXTENDED_END.minute);\n\n if (calendar.isEarlyCloseDay(date)) {\n close = buildNYTime(MARKET_CONFIG.TIMES.EARLY_CLOSE.hour, MARKET_CONFIG.TIMES.EARLY_CLOSE.minute);\n closeExt = buildNYTime(MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.hour, MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.minute);\n }\n\n return {\n marketOpen: true,\n open,\n close,\n openExt,\n closeExt,\n };\n}\n\n// Is within market hours\n/**\n * Checks if a date/time is within market hours, extended hours, or continuous.\n * @param date - Date object\n * @param intradayReporting - 'market_hours', 'extended_hours', or 'continuous'\n * @returns true if within hours, false otherwise\n */\nexport function isWithinMarketHours(date: Date, intradayReporting: IntradayReporting = 'market_hours'): boolean {\n const calendar = new MarketCalendar();\n if (!calendar.isMarketDay(date)) return false;\n const nyDate = toNYTime(date);\n const minutes = nyDate.getUTCHours() * 60 + nyDate.getUTCMinutes();\n\n switch (intradayReporting) {\n case 'extended_hours': {\n let endMinutes = MARKET_CONFIG.TIMES.EXTENDED_END.hour * 60 + MARKET_CONFIG.TIMES.EXTENDED_END.minute;\n if (calendar.isEarlyCloseDay(date)) {\n endMinutes = MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.hour * 60 + MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.minute;\n }\n const startMinutes = MARKET_CONFIG.TIMES.EXTENDED_START.hour * 60 + MARKET_CONFIG.TIMES.EXTENDED_START.minute;\n return minutes >= startMinutes && minutes <= endMinutes;\n }\n case 'continuous':\n return true;\n default: {\n let endMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n if (calendar.isEarlyCloseDay(date)) {\n endMinutes = MARKET_CONFIG.TIMES.EARLY_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.EARLY_CLOSE.minute;\n }\n const startMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n return minutes >= startMinutes && minutes <= endMinutes;\n }\n }\n}\n\n// Get last full trading date\n/**\n * Returns the last full trading date (market close) for a given date.\n * @param currentDate - Date object (default: now)\n * @returns Date object for last full trading date\n */\nfunction getLastFullTradingDateImpl(currentDate: Date = new Date()): Date {\n const calendar = new MarketCalendar();\n const nyDate = toNYTime(currentDate);\n const minutes = nyDate.getUTCHours() * 60 + nyDate.getUTCMinutes();\n const marketOpenMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n let marketCloseMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n if (calendar.isEarlyCloseDay(currentDate)) {\n marketCloseMinutes = MARKET_CONFIG.TIMES.EARLY_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.EARLY_CLOSE.minute;\n }\n\n // If not a market day, or before open, or during market hours, return previous market day's close\n if (\n !calendar.isMarketDay(currentDate) ||\n minutes < marketOpenMinutes ||\n (minutes >= marketOpenMinutes && minutes < marketCloseMinutes)\n ) {\n const prevMarketDay = calendar.getPreviousMarketDay(currentDate);\n let prevCloseMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n if (calendar.isEarlyCloseDay(prevMarketDay)) {\n prevCloseMinutes = MARKET_CONFIG.TIMES.EARLY_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.EARLY_CLOSE.minute;\n }\n const prevNYDate = toNYTime(prevMarketDay);\n const year = prevNYDate.getUTCFullYear();\n const month = prevNYDate.getUTCMonth();\n const day = prevNYDate.getUTCDate();\n const closeHour = Math.floor(prevCloseMinutes / 60);\n const closeMinute = prevCloseMinutes % 60;\n return fromNYTime(new Date(Date.UTC(year, month, day, closeHour, closeMinute, 0, 0)));\n }\n\n // After market close or after extended hours, return today's close\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth();\n const day = nyDate.getUTCDate();\n const closeHour = Math.floor(marketCloseMinutes / 60);\n const closeMinute = marketCloseMinutes % 60;\n return fromNYTime(new Date(Date.UTC(year, month, day, closeHour, closeMinute, 0, 0)));\n}\n\n// Get day boundaries\n/**\n * Returns the start and end boundaries for a market day, extended hours, or continuous.\n * @param date - Date object\n * @param intradayReporting - 'market_hours', 'extended_hours', or 'continuous'\n * @returns Object with start and end Date\n */\nfunction getDayBoundaries(\n date: Date,\n intradayReporting: IntradayReporting = 'market_hours'\n): { start: Date; end: Date } {\n const calendar = new MarketCalendar();\n const nyDate = toNYTime(date);\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth();\n const day = nyDate.getUTCDate();\n\n function buildNYTime(hour: number, minute: number, sec = 0, ms = 0): Date {\n const d = new Date(Date.UTC(year, month, day, hour, minute, sec, ms));\n return fromNYTime(d);\n }\n\n let start: Date;\n let end: Date;\n\n switch (intradayReporting) {\n case 'extended_hours':\n start = buildNYTime(MARKET_CONFIG.TIMES.EXTENDED_START.hour, MARKET_CONFIG.TIMES.EXTENDED_START.minute, 0, 0);\n end = buildNYTime(MARKET_CONFIG.TIMES.EXTENDED_END.hour, MARKET_CONFIG.TIMES.EXTENDED_END.minute, 59, 999);\n if (calendar.isEarlyCloseDay(date)) {\n end = buildNYTime(\n MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.hour,\n MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.minute,\n 59,\n 999\n );\n }\n break;\n case 'continuous':\n start = new Date(Date.UTC(year, month, day, 0, 0, 0, 0));\n end = new Date(Date.UTC(year, month, day, 23, 59, 59, 999));\n break;\n default:\n start = buildNYTime(MARKET_CONFIG.TIMES.MARKET_OPEN.hour, MARKET_CONFIG.TIMES.MARKET_OPEN.minute, 0, 0);\n end = buildNYTime(MARKET_CONFIG.TIMES.MARKET_CLOSE.hour, MARKET_CONFIG.TIMES.MARKET_CLOSE.minute, 59, 999);\n if (calendar.isEarlyCloseDay(date)) {\n end = buildNYTime(MARKET_CONFIG.TIMES.EARLY_CLOSE.hour, MARKET_CONFIG.TIMES.EARLY_CLOSE.minute, 59, 999);\n }\n break;\n }\n return { start, end };\n}\n\n// Period calculator\n/**\n * Calculates the start date for a given period ending at endDate.\n * @param endDate - Date object\n * @param period - Period string\n * @returns Date object for period start\n */\nfunction calculatePeriodStartDate(endDate: Date, period: Period): Date {\n const calendar = new MarketCalendar();\n let startDate: Date;\n switch (period) {\n case 'YTD':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear(), 0, 1));\n break;\n case '1D':\n startDate = calendar.getPreviousMarketDay(endDate);\n break;\n case '3D':\n startDate = new Date(endDate.getTime() - 3 * 24 * 60 * 60 * 1000);\n break;\n case '1W':\n startDate = new Date(endDate.getTime() - 7 * 24 * 60 * 60 * 1000);\n break;\n case '2W':\n startDate = new Date(endDate.getTime() - 14 * 24 * 60 * 60 * 1000);\n break;\n case '1M':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear(), endDate.getUTCMonth() - 1, endDate.getUTCDate()));\n break;\n case '3M':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear(), endDate.getUTCMonth() - 3, endDate.getUTCDate()));\n break;\n case '6M':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear(), endDate.getUTCMonth() - 6, endDate.getUTCDate()));\n break;\n case '1Y':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear() - 1, endDate.getUTCMonth(), endDate.getUTCDate()));\n break;\n default:\n throw new Error(`Invalid period: ${period}`);\n }\n // Ensure start date is a market day\n while (!calendar.isMarketDay(startDate)) {\n startDate = calendar.getNextMarketDay(startDate);\n }\n return startDate;\n}\n\n// Get market time period\n/**\n * Returns the start and end dates for a market time period.\n * @param params - MarketTimeParams\n * @returns PeriodDates object\n */\nexport function getMarketTimePeriod(params: MarketTimeParams): PeriodDates {\n const { period, end = new Date(), intraday_reporting = 'market_hours', outputFormat = 'iso' } = params;\n\n if (!period) throw new Error('Period is required');\n const calendar = new MarketCalendar();\n\n const nyEndDate = toNYTime(end);\n let endDate: Date;\n const isCurrentMarketDay = calendar.isMarketDay(end);\n const isWithinHours = isWithinMarketHours(end, intraday_reporting);\n const minutes = nyEndDate.getUTCHours() * 60 + nyEndDate.getUTCMinutes();\n const marketStartMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n\n if (isCurrentMarketDay) {\n if (minutes < marketStartMinutes) {\n // Before market open - use previous day's close\n const lastMarketDay = calendar.getPreviousMarketDay(end);\n const { end: dayEnd } = getDayBoundaries(lastMarketDay, intraday_reporting);\n endDate = dayEnd;\n } else if (isWithinHours) {\n // During market hours - use current time\n endDate = end;\n } else {\n // After market close - use today's close\n const { end: dayEnd } = getDayBoundaries(end, intraday_reporting);\n endDate = dayEnd;\n }\n } else {\n // Not a market day - use previous market day's close\n const lastMarketDay = calendar.getPreviousMarketDay(end);\n const { end: dayEnd } = getDayBoundaries(lastMarketDay, intraday_reporting);\n endDate = dayEnd;\n }\n\n // Calculate start date\n const periodStartDate = calculatePeriodStartDate(endDate, period);\n const { start: dayStart } = getDayBoundaries(periodStartDate, intraday_reporting);\n\n if (endDate.getTime() < dayStart.getTime()) {\n throw new Error('Start date cannot be after end date');\n }\n\n return {\n start: formatDate(dayStart, outputFormat),\n end: formatDate(endDate, outputFormat),\n };\n}\n\n// Market status\n/**\n * Returns the current market status for a given date.\n * @param date - Date object (default: now)\n * @returns MarketStatus object\n */\nfunction getMarketStatusImpl(date: Date = new Date()): MarketStatus {\n const calendar = new MarketCalendar();\n const nyDate = toNYTime(date);\n const minutes = nyDate.getUTCHours() * 60 + nyDate.getUTCMinutes();\n const isMarketDay = calendar.isMarketDay(date);\n const isEarlyCloseDay = calendar.isEarlyCloseDay(date);\n\n const extendedStartMinutes = MARKET_CONFIG.TIMES.EXTENDED_START.hour * 60 + MARKET_CONFIG.TIMES.EXTENDED_START.minute;\n const marketStartMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n const earlyMarketEndMinutes =\n MARKET_CONFIG.TIMES.EARLY_MARKET_END.hour * 60 + MARKET_CONFIG.TIMES.EARLY_MARKET_END.minute;\n\n let marketCloseMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n let extendedEndMinutes = MARKET_CONFIG.TIMES.EXTENDED_END.hour * 60 + MARKET_CONFIG.TIMES.EXTENDED_END.minute;\n if (isEarlyCloseDay) {\n marketCloseMinutes = MARKET_CONFIG.TIMES.EARLY_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.EARLY_CLOSE.minute;\n extendedEndMinutes =\n MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.hour * 60 + MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.minute;\n }\n\n let status: MarketStatus['status'];\n let nextStatus: MarketStatus['nextStatus'];\n let nextStatusTime: Date;\n let marketPeriod: MarketStatus['marketPeriod'];\n\n if (!isMarketDay) {\n status = 'closed';\n nextStatus = 'extended hours';\n marketPeriod = 'closed';\n const nextMarketDay = calendar.getNextMarketDay(date);\n nextStatusTime = getDayBoundaries(nextMarketDay, 'extended_hours').start;\n } else if (minutes < extendedStartMinutes) {\n status = 'closed';\n nextStatus = 'extended hours';\n marketPeriod = 'closed';\n nextStatusTime = getDayBoundaries(date, 'extended_hours').start;\n } else if (minutes < marketStartMinutes) {\n status = 'extended hours';\n nextStatus = 'open';\n marketPeriod = 'preMarket';\n nextStatusTime = getDayBoundaries(date, 'market_hours').start;\n } else if (minutes < marketCloseMinutes) {\n status = 'open';\n nextStatus = 'extended hours';\n marketPeriod = minutes < earlyMarketEndMinutes ? 'earlyMarket' : 'regularMarket';\n nextStatusTime = getDayBoundaries(date, 'market_hours').end;\n } else if (minutes < extendedEndMinutes) {\n status = 'extended hours';\n nextStatus = 'closed';\n marketPeriod = 'afterMarket';\n nextStatusTime = getDayBoundaries(date, 'extended_hours').end;\n } else {\n status = 'closed';\n nextStatus = 'extended hours';\n marketPeriod = 'closed';\n const nextMarketDay = calendar.getNextMarketDay(date);\n nextStatusTime = getDayBoundaries(nextMarketDay, 'extended_hours').start;\n }\n\n // I think using nyDate here may be wrong - should use current time? i.e. date.getTime()\n const nextStatusTimeDifference = nextStatusTime.getTime() - date.getTime();\n\n return {\n time: date,\n timeString: formatNYLocale(nyDate),\n status,\n nextStatus,\n marketPeriod,\n nextStatusTime,\n nextStatusTimeDifference,\n nextStatusTimeString: formatNYLocale(nextStatusTime),\n };\n}\n\n// API exports\n/**\n * Returns market open/close times for a given date.\n * @param options - { date?: Date }\n * @returns MarketOpenCloseResult\n */\nexport function getMarketOpenClose(options: { date?: Date } = {}): MarketOpenCloseResult {\n const { date = new Date() } = options;\n return getMarketTimes(date);\n}\n\n/**\n * Returns the start and end dates for a market time period as Date objects.\n * @param params - MarketTimeParams\n * @returns Object with start and end Date\n */\nexport function getStartAndEndDates(params: MarketTimeParams = {}): { start: Date; end: Date } {\n const { start, end } = getMarketTimePeriod(params);\n return {\n start: typeof start === 'string' || typeof start === 'number' ? new Date(start) : start,\n end: typeof end === 'string' || typeof end === 'number' ? new Date(end) : end,\n };\n}\n\n/**\n * Returns the last full trading date as a Date object.\n */\n/**\n * Returns the last full trading date as a Date object.\n * @param currentDate - Date object (default: now)\n * @returns Date object for last full trading date\n */\nexport function getLastFullTradingDate(currentDate: Date = new Date()): Date {\n return getLastFullTradingDateImpl(currentDate);\n}\n\n/**\n * Returns the last full trading date and formatted YYYYMMDD string.\n */\n/**\n * Returns the last full trading date and formatted YYYY-MM-DD string.\n * @param currentDate - Date object (default: now)\n * @returns Object with date and YYYYMMDD string\n */\nexport function getLastFullTradingDateInfo(currentDate: Date = new Date()): { date: Date; YYYYMMDD: string } {\n const date = getLastFullTradingDateImpl(currentDate);\n return {\n date,\n YYYYMMDD: `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}-${String(\n date.getUTCDate()\n ).padStart(2, '0')}`,\n };\n}\n\n/**\n * Returns the next market day after the reference date.\n * @param referenceDate - Date object (default: now)\n * @returns Object with date, yyyymmdd string, and ISO string\n */\nexport function getNextMarketDay({ referenceDate }: { referenceDate?: Date } = {}): {\n date: Date;\n yyyymmdd: string;\n dateISOString: string;\n} {\n const calendar = new MarketCalendar();\n const startDate = referenceDate ?? new Date();\n\n // Find the next trading day (UTC Date object)\n const nextDate = calendar.getNextMarketDay(startDate);\n\n // Convert to NY time before extracting Y-M-D parts\n const nyNext = toNYTime(nextDate);\n const yyyymmdd = `${nyNext.getUTCFullYear()}-${String(nyNext.getUTCMonth() + 1).padStart(2, '0')}-${String(\n nyNext.getUTCDate()\n ).padStart(2, '0')}`;\n\n return {\n date: nextDate, // raw Date, unchanged\n yyyymmdd, // correct trading date string\n dateISOString: nextDate.toISOString(),\n };\n}\n\n/**\n * Returns the previous market day before the reference date.\n * @param referenceDate - Date object (default: now)\n * @returns Object with date, yyyymmdd string, and ISO string\n */\nexport function getPreviousMarketDay({ referenceDate }: { referenceDate?: Date } = {}) {\n const calendar = new MarketCalendar();\n const startDate = referenceDate || new Date();\n const prevDate = calendar.getPreviousMarketDay(startDate);\n\n // convert to NY time first\n const nyPrev = toNYTime(prevDate); // \u2190 already in this file\n const yyyymmdd = `${nyPrev.getUTCFullYear()}-${String(nyPrev.getUTCMonth() + 1).padStart(2, '0')}-${String(\n nyPrev.getUTCDate()\n ).padStart(2, '0')}`;\n\n return {\n date: prevDate,\n yyyymmdd,\n dateISOString: prevDate.toISOString(),\n };\n}\n\n/**\n * Returns the trading date for a given time. Note: Just trims the date string; does not validate if the date is a market day.\n * @param time - a string, number (unix timestamp), or Date object representing the time\n * @returns the trading date as a string in YYYY-MM-DD format\n */\n/**\n * Returns the trading date for a given time in YYYY-MM-DD format (NY time).\n * @param time - string, number, or Date\n * @returns trading date string\n */\nexport function getTradingDate(time: string | number | Date): string {\n const date = typeof time === 'number' ? new Date(time) : typeof time === 'string' ? new Date(time) : time;\n const nyDate = toNYTime(date);\n return `${nyDate.getUTCFullYear()}-${String(nyDate.getUTCMonth() + 1).padStart(2, '0')}-${String(\n nyDate.getUTCDate()\n ).padStart(2, '0')}`;\n}\n\n/**\n * Returns the NY timezone offset string for a given date.\n * @param date - Date object (default: now)\n * @returns '-04:00' for EDT, '-05:00' for EST\n */\nexport function getNYTimeZone(date?: Date): '-04:00' | '-05:00' {\n const offset = getNYOffset(date || new Date());\n return offset === -4 ? '-04:00' : '-05:00';\n}\n\n/**\n * Returns the regular market open and close Date objects for a given trading day string in the\n * America/New_York timezone (NYSE/NASDAQ calendar).\n *\n * This helper is convenient when you have a calendar date like '2025-10-03' and want the precise\n * open and close Date values for that day. It internally:\n * - Determines the NY offset for the day using `getNYTimeZone()`.\n * - Anchors a noon-time Date on that day in NY time to avoid DST edge cases.\n * - Verifies the day is a market day via `isMarketDay()`.\n * - Fetches the open/close times via `getMarketOpenClose()`.\n *\n * Throws if the provided day is not a market day or if open/close times are unavailable.\n *\n * See also:\n * - `getNYTimeZone(date?: Date)`\n * - `isMarketDay(date: Date)`\n * - `getMarketOpenClose(options?: { date?: Date })`\n *\n * @param dateStr - Trading day string in 'YYYY-MM-DD' format (Eastern Time date)\n * @returns An object containing `{ open: Date; close: Date }`\n * @example\n * ```ts\n * const { open, close } = disco.time.getOpenCloseForTradingDay('2025-10-03');\n * ```\n */\nexport function getOpenCloseForTradingDay(dateStr: string): { open: Date; close: Date } {\n // Build a UTC midnight anchor for the date, then derive the NY offset for that day.\n const utcAnchor = new Date(`${dateStr}T00:00:00Z`);\n const nyOffset = getNYTimeZone(utcAnchor); // '-04:00' | '-05:00'\n\n // Create a NY-local noon date to avoid DST midnight transitions.\n const nyNoon = new Date(`${dateStr}T12:00:00${nyOffset}`);\n\n if (!isMarketDay(nyNoon)) {\n throw new Error(`Not a market day in ET: ${dateStr}`);\n }\n\n const { open, close } = getMarketOpenClose({ date: nyNoon });\n if (!open || !close) {\n throw new Error(`No market times available for ${dateStr}`);\n }\n\n return { open, close };\n}\n\n/**\n * Converts any date to the market time zone (America/New_York, Eastern Time).\n * Returns a new Date object representing the same moment in time but adjusted to NY/Eastern timezone.\n * Automatically handles daylight saving time transitions (EST/EDT).\n * \n * @param date - Date object to convert to market time zone\n * @returns Date object in NY/Eastern time zone\n * @example\n * ```typescript\n * const utcDate = new Date('2024-01-15T15:30:00Z'); // 3:30 PM UTC\n * const nyDate = convertDateToMarketTimeZone(utcDate); // 10:30 AM EST (winter) or 11:30 AM EDT (summer)\n * ```\n */\nexport function convertDateToMarketTimeZone(date: Date): Date {\n return toNYTime(date);\n}\n\n/**\n * Returns the current market status for a given date.\n * @param options - { date?: Date }\n * @returns MarketStatus object\n */\nexport function getMarketStatus(options: { date?: Date } = {}): MarketStatus {\n const { date = new Date() } = options;\n return getMarketStatusImpl(date);\n}\n\n/**\n * Checks if a date is a market day.\n * @param date - Date object\n * @returns true if market day, false otherwise\n */\nexport function isMarketDay(date: Date): boolean {\n const calendar = new MarketCalendar();\n return calendar.isMarketDay(date);\n}\n\n/**\n * Returns full trading days from market open to market close.\n * endDate is always the most recent market close (previous day's close if before open, today's close if after open).\n * days: 1 or not specified = that day's open; 2 = previous market day's open, etc.\n */\n/**\n * Returns full trading days from market open to market close.\n * @param options - { endDate?: Date, days?: number }\n * @returns Object with startDate and endDate\n */\nexport function getTradingStartAndEndDates(\n options: {\n endDate?: Date;\n days?: number;\n } = {}\n): { startDate: Date; endDate: Date } {\n const { endDate = new Date(), days = 1 } = options;\n const calendar = new MarketCalendar();\n\n // Find the most recent market close\n let endMarketDay = endDate;\n const nyEnd = toNYTime(endDate);\n const marketOpenMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n const marketCloseMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n const minutes = nyEnd.getUTCHours() * 60 + nyEnd.getUTCMinutes();\n\n if (\n !calendar.isMarketDay(endDate) ||\n minutes < marketOpenMinutes ||\n (minutes >= marketOpenMinutes && minutes < marketCloseMinutes)\n ) {\n // Before market open, not a market day, or during market hours: use previous market day\n endMarketDay = calendar.getPreviousMarketDay(endDate);\n } else {\n // After market close: use today\n endMarketDay = endDate;\n }\n\n // Get market close for endMarketDay\n const endClose = getMarketOpenClose({ date: endMarketDay }).close!;\n\n // Find start market day by iterating back over market days\n let startMarketDay = endMarketDay;\n let count = Math.max(1, days);\n for (let i = 1; i < count; i++) {\n startMarketDay = calendar.getPreviousMarketDay(startMarketDay);\n }\n // If days > 1, we need to go back (days-1) market days from endMarketDay\n if (days > 1) {\n startMarketDay = endMarketDay;\n for (let i = 1; i < days; i++) {\n startMarketDay = calendar.getPreviousMarketDay(startMarketDay);\n }\n }\n const startOpen = getMarketOpenClose({ date: startMarketDay }).open!;\n\n return { startDate: startOpen, endDate: endClose };\n}\n\n/**\n * Counts trading time between two dates (passed as standard Date objects), excluding weekends and holidays, and closed market hours, using other functions in this library.\n *\n * This function calculates the actual trading time between two dates by:\n * 1. Iterating through each calendar day between startDate and endDate (inclusive)\n * 2. For each day that is a market day (not weekend/holiday), getting market open/close times\n * 3. Calculating the overlap between the time range and market hours for that day\n * 4. Summing up all the trading minutes across all days\n *\n * The function automatically handles:\n * - Weekends (Saturday/Sunday) - skipped entirely\n * - Market holidays - skipped entirely\n * - Early close days (e.g. day before holidays) - uses early close time\n * - Times outside market hours - only counts time within 9:30am-4pm ET (or early close)\n *\n * Examples:\n * - 12pm to 3:30pm same day = 3.5 hours = 210 minutes = 0.54 days\n * - 9:30am to 4pm same day = 6.5 hours = 390 minutes = 1 day\n * - Friday 2pm to Monday 2pm = 6.5 hours (Friday 2pm-4pm + Monday 9:30am-2pm)\n *\n * @param startDate - Start date/time\n * @param endDate - End date/time (default: now)\n * @returns Object containing:\n * - days: Trading time as fraction of full trading days (6.5 hours = 1 day)\n * - hours: Trading time in hours\n * - minutes: Trading time in minutes\n */\nexport function countTradingDays(\n startDate: Date,\n endDate: Date = new Date()\n): {\n days: number;\n hours: number;\n minutes: number;\n} {\n const calendar = new MarketCalendar();\n\n // Ensure start is before end\n if (startDate.getTime() > endDate.getTime()) {\n throw new Error('Start date must be before end date');\n }\n\n let totalMinutes = 0;\n\n // Get the NY dates for iteration\n const startNY = toNYTime(startDate);\n const endNY = toNYTime(endDate);\n\n // Create date at start of first day (in NY time)\n const currentNY = new Date(\n Date.UTC(startNY.getUTCFullYear(), startNY.getUTCMonth(), startNY.getUTCDate(), 0, 0, 0, 0)\n );\n\n // Iterate through each calendar day\n while (currentNY.getTime() <= endNY.getTime()) {\n const currentUTC = fromNYTime(currentNY);\n\n // Check if this is a market day\n if (calendar.isMarketDay(currentUTC)) {\n // Get market hours for this day\n const marketTimes = getMarketTimes(currentUTC);\n\n if (marketTimes.marketOpen && marketTimes.open && marketTimes.close) {\n // Calculate the overlap between our time range and market hours\n const dayStart = Math.max(startDate.getTime(), marketTimes.open.getTime());\n const dayEnd = Math.min(endDate.getTime(), marketTimes.close.getTime());\n\n // Only count if there's actual overlap\n if (dayStart < dayEnd) {\n totalMinutes += (dayEnd - dayStart) / (1000 * 60);\n }\n }\n }\n\n // Move to next day\n currentNY.setUTCDate(currentNY.getUTCDate() + 1);\n }\n\n // Convert to days, hours, minutes\n const MINUTES_PER_TRADING_DAY = 390; // 6.5 hours\n const days = totalMinutes / MINUTES_PER_TRADING_DAY;\n const hours = totalMinutes / 60;\n const minutes = totalMinutes;\n\n return {\n days: Math.round(days * 1000) / 1000, // Round to 3 decimal places\n hours: Math.round(hours * 100) / 100, // Round to 2 decimal places\n minutes: Math.round(minutes),\n };\n}\n\n/**\n * Returns the trading day N days back from a reference date, along with its market open time.\n * Trading days are counted as full or half trading days (days that end count as 1 full trading day).\n * By default, the most recent completed trading day counts as day 1.\n * Set includeMostRecentFullDay to false to count strictly before that day.\n * \n * @param options - Object with:\n * - referenceDate: Date to count back from (default: now)\n * - days: Number of trading days to go back (must be an integer >= 1)\n * - includeMostRecentFullDay: Whether to include the most recent completed trading day (default: true)\n * @returns Object containing:\n * - date: Trading date in YYYY-MM-DD format\n * - marketOpenISO: Market open time as ISO string (e.g., \"2025-11-15T13:30:00.000Z\")\n * - unixTimestamp: Market open time as Unix timestamp in seconds\n * @example\n * ```typescript\n * // Get the trading day 1 day back (most recent full trading day)\n * const result = getTradingDaysBack({ days: 1 });\n * console.log(result.date); // \"2025-11-01\"\n * console.log(result.marketOpenISO); // \"2025-11-01T13:30:00.000Z\"\n * console.log(result.unixTimestamp); // 1730466600\n * \n * // Get the trading day 5 days back from a specific date\n * const result2 = getTradingDaysBack({ \n * referenceDate: new Date('2025-11-15T12:00:00-05:00'), \n * days: 5 \n * });\n * ```\n */\nexport function getTradingDaysBack(options: TradingDaysBackOptions): {\n date: string;\n marketOpenISO: string;\n unixTimestamp: number;\n} {\n const calendar = new MarketCalendar();\n const { referenceDate, days, includeMostRecentFullDay = true } = options;\n const refDate = referenceDate || new Date();\n const daysBack = days;\n\n if (!Number.isInteger(daysBack) || daysBack < 1) {\n throw new Error('days must be an integer >= 1');\n }\n\n // Start from the last full trading date relative to reference\n let targetDate = getLastFullTradingDateImpl(refDate);\n\n if (!includeMostRecentFullDay) {\n targetDate = calendar.getPreviousMarketDay(targetDate);\n }\n\n // Go back the specified number of days (we're already at day 1, so go back days-1 more)\n for (let i = 1; i < daysBack; i++) {\n targetDate = calendar.getPreviousMarketDay(targetDate);\n }\n\n // Get market open time for this date\n const marketTimes = getMarketTimes(targetDate);\n if (!marketTimes.open) {\n throw new Error(`No market open time for target date`);\n }\n\n // Format the date string (YYYY-MM-DD) in NY time\n const nyDate = toNYTime(marketTimes.open);\n const dateStr = `${nyDate.getUTCFullYear()}-${String(nyDate.getUTCMonth() + 1).padStart(2, '0')}-${String(nyDate.getUTCDate()).padStart(2, '0')}`;\n\n const marketOpenISO = marketTimes.open.toISOString();\n const unixTimestamp = Math.floor(marketTimes.open.getTime() / 1000);\n\n return {\n date: dateStr,\n marketOpenISO,\n unixTimestamp,\n };\n}\n\n// Export MARKET_TIMES for compatibility\nexport const MARKET_TIMES: MarketTimesConfig = {\n TIMEZONE: MARKET_CONFIG.TIMEZONE,\n PRE: {\n START: { HOUR: 4, MINUTE: 0, MINUTES: 240 },\n END: { HOUR: 9, MINUTE: 30, MINUTES: 570 },\n },\n EARLY_MORNING: {\n START: { HOUR: 9, MINUTE: 30, MINUTES: 570 },\n END: { HOUR: 10, MINUTE: 0, MINUTES: 600 },\n },\n EARLY_CLOSE_BEFORE_HOLIDAY: {\n START: { HOUR: 9, MINUTE: 30, MINUTES: 570 },\n END: { HOUR: 13, MINUTE: 0, MINUTES: 780 },\n },\n EARLY_EXTENDED_BEFORE_HOLIDAY: {\n START: { HOUR: 13, MINUTE: 0, MINUTES: 780 },\n END: { HOUR: 17, MINUTE: 0, MINUTES: 1020 },\n },\n REGULAR: {\n START: { HOUR: 9, MINUTE: 30, MINUTES: 570 },\n END: { HOUR: 16, MINUTE: 0, MINUTES: 960 },\n },\n EXTENDED: {\n START: { HOUR: 4, MINUTE: 0, MINUTES: 240 },\n END: { HOUR: 20, MINUTE: 0, MINUTES: 1200 },\n },\n};\n", "// market-hours.ts\n\nexport interface HolidayDetails {\n date: string;\n}\n\nexport interface MarketHolidaysForYear {\n [holidayName: string]: HolidayDetails;\n}\n\nexport interface MarketHolidays {\n [year: number]: MarketHolidaysForYear;\n}\n\nexport interface EarlyCloseDetails {\n date: string;\n time: string;\n optionsTime: string;\n notes: string;\n}\n\nexport interface EarlyClosesForYear {\n [date: string]: EarlyCloseDetails;\n}\n\nexport interface MarketEarlyCloses {\n [year: number]: EarlyClosesForYear;\n}\n\nexport const marketHolidays: MarketHolidays = {\n 2024: {\n \"New Year's Day\": { date: '2024-01-01' },\n 'Martin Luther King, Jr. Day': { date: '2024-01-15' },\n \"Washington's Birthday\": { date: '2024-02-19' },\n 'Good Friday': { date: '2024-03-29' },\n 'Memorial Day': { date: '2024-05-27' },\n 'Juneteenth National Independence Day': { date: '2024-06-19' },\n 'Independence Day': { date: '2024-07-04' },\n 'Labor Day': { date: '2024-09-02' },\n 'Thanksgiving Day': { date: '2024-11-28' },\n 'Christmas Day': { date: '2024-12-25' },\n },\n 2025: {\n \"New Year's Day\": { date: '2025-01-01' },\n 'Jimmy Carter Memorial Day': { date: '2025-01-09' },\n 'Martin Luther King, Jr. Day': { date: '2025-01-20' },\n \"Washington's Birthday\": { date: '2025-02-17' },\n 'Good Friday': { date: '2025-04-18' },\n 'Memorial Day': { date: '2025-05-26' },\n 'Juneteenth National Independence Day': { date: '2025-06-19' },\n 'Independence Day': { date: '2025-07-04' },\n 'Labor Day': { date: '2025-09-01' },\n 'Thanksgiving Day': { date: '2025-11-27' },\n 'Christmas Day': { date: '2025-12-25' },\n },\n 2026: {\n \"New Year's Day\": { date: '2026-01-01' },\n 'Martin Luther King, Jr. Day': { date: '2026-01-19' },\n \"Washington's Birthday\": { date: '2026-02-16' },\n 'Good Friday': { date: '2026-04-03' },\n 'Memorial Day': { date: '2026-05-25' },\n 'Juneteenth National Independence Day': { date: '2026-06-19' },\n 'Independence Day': { date: '2026-07-03' },\n 'Labor Day': { date: '2026-09-07' },\n 'Thanksgiving Day': { date: '2026-11-26' },\n 'Christmas Day': { date: '2026-12-25' },\n },\n};\n\nexport const marketEarlyCloses: MarketEarlyCloses = {\n 2024: {\n '2024-07-03': {\n date: '2024-07-03',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Wednesday, July 3, 2024 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2024-11-29': {\n date: '2024-11-29',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Friday, November 29, 2024 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2024-12-24': {\n date: '2024-12-24',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Tuesday, December 24, 2024 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n },\n 2025: {\n '2025-07-03': {\n date: '2025-07-03',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Thursday, July 3, 2025 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2025-11-28': {\n date: '2025-11-28',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Friday, November 28, 2025 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2025-12-24': {\n date: '2025-12-24',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Wednesday, December 24, 2025 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n },\n 2026: {\n '2026-07-02': {\n date: '2026-07-02',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Independence Day observed, market closes early at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2026-11-27': {\n date: '2026-11-27',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Friday, November 27, 2026 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2026-12-24': {\n date: '2026-12-24',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Thursday, December 24, 2026 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n },\n};\n"],
4
+ "sourcesContent": ["/* Front-end only exports.\nImport these with `import { disco } from 'disco-core/frontend'` \n*/\n\n\nimport * as Types from './types';\nimport * as llm from './llm-openai';\nimport * as llmImages from './llm-images';\nimport * as deepseek from './llm-deepseek';\nimport * as time from './market-time';\n\n// Re-export all types\nexport * from './types';\nexport { supportsTemperature, uploadVisionFile } from './llm-openai';\nexport { OPENAI_MODELS, OPENROUTER_MODELS } from './types/llm-types';\n\nexport const disco = {\n types: Types,\n llm: {\n call: llm.makeLLMCall,\n uploadVisionFile: llm.uploadVisionFile,\n seek: deepseek.makeDeepseekCall,\n images: llmImages.makeImagesCall,\n },\n time,\n};\n", "export * from './alpaca-types';\nexport * from './market-time-types';\nexport * from './ta-types';\nexport * from './llm-types';\nexport * from './logging-types';\nexport * from './disco-mail-types';\n", "// openai-types.ts\nimport type {\n ChatCompletionMessageParam,\n ChatCompletionTool,\n ChatCompletionMessageToolCall,\n} from 'openai/resources/chat/completions';\nimport type { ImageGenerateParams, ImageModel } from 'openai/resources/images';\nimport type { ResponseFormatTextJSONSchemaConfig, ResponseInputImage } from 'openai/resources/responses/responses';\nimport type { ZodType } from 'zod';\n\n/**\n * Represents OpenAI models\n */\nexport const OPENAI_MODELS = [\n 'gpt-5.6',\n 'gpt-5.6-sol',\n 'gpt-5.6-terra',\n 'gpt-5.6-luna',\n 'gpt-5',\n 'gpt-5-mini',\n 'gpt-5.4-mini',\n 'gpt-5.4-nano',\n 'gpt-5-nano',\n 'gpt-5.1',\n 'gpt-5.4',\n 'gpt-5.5',\n 'gpt-5.5-pro',\n 'gpt-5.2',\n 'gpt-5.2-pro',\n 'gpt-5.1-codex',\n 'gpt-5.1-codex-max',\n] as const;\n\nexport type OpenAIModel = (typeof OPENAI_MODELS)[number];\n\n/**\n * Type guard to check if a model is a supported direct OpenAI model.\n */\nexport function isOpenAIModel(model: string): model is OpenAIModel {\n return OPENAI_MODELS.includes(model as OpenAIModel);\n}\n\n/**\n * Represents OpenAI image models.\n */\nexport const OPENAI_IMAGE_MODELS = [\n 'gpt-image-2',\n 'gpt-image-2-2026-04-21',\n 'gpt-image-1.5',\n 'gpt-image-1',\n 'gpt-image-1-mini',\n 'chatgpt-image-latest',\n 'dall-e-2',\n 'dall-e-3',\n] as const satisfies readonly ImageModel[];\n\nexport type OpenAIImageModel = (typeof OPENAI_IMAGE_MODELS)[number];\n\n/**\n * Type guard to check if a model is a supported OpenAI image model.\n */\nexport function isOpenAIImageModel(model: string): model is OpenAIImageModel {\n return OPENAI_IMAGE_MODELS.includes(model as OpenAIImageModel);\n}\n\n/**\n * Represents Deepseek models\n */\nexport type DeepseekModel = 'deepseek-chat' | 'deepseek-reasoner';\n\n/**\n * Represents OpenRouter models\n */\nexport const OPENROUTER_MODELS = [\n 'openai/gpt-5',\n 'openai/gpt-5-mini',\n 'openai/gpt-5.4-mini',\n 'openai/gpt-5.4-nano',\n 'openai/gpt-5-nano',\n 'openai/gpt-5.1',\n 'openai/gpt-5.4',\n 'openai/gpt-5.4-pro',\n 'openai/gpt-5.5',\n 'openai/gpt-5.5-pro',\n 'openai/gpt-5.2',\n 'openai/gpt-5.2-pro',\n 'openai/gpt-5.1-codex',\n 'openai/gpt-5.1-codex-max',\n 'openai/gpt-oss-120b',\n 'z.ai/glm-4.5',\n 'z.ai/glm-4.5-air',\n 'google/gemini-2.5-flash',\n 'google/gemini-2.5-flash-lite',\n 'deepseek/deepseek-r1-0528',\n 'deepseek/deepseek-chat-v3-0324',\n] as const;\n\nexport type OpenRouterModel = (typeof OPENROUTER_MODELS)[number];\n\n/**\n * Represents pricing information for OpenRouter models\n */\nexport interface OpenRouterPricing {\n input: number; // Cost per 1M input tokens\n output: number; // Cost per 1M output tokens\n context?: number; // Max context tokens\n}\n\n/**\n * Represents all supported LLM models\n */\nexport type LLMModel = OpenAIModel | DeepseekModel | OpenRouterModel;\n\n/**\n * Type guard to check if a model is an OpenRouter model\n */\nexport function isOpenRouterModel(model: string): model is OpenRouterModel {\n return OPENROUTER_MODELS.includes(model as OpenRouterModel);\n}\n\n/**\n * Represents the usage of the LLM.\n */\nexport interface LLMUsage {\n prompt_tokens: number;\n completion_tokens: number;\n reasoning_tokens?: number;\n provider: string;\n model: LLMModel;\n cache_hit_tokens?: number;\n cache_write_tokens?: number;\n cost: number;\n}\n\n/**\n * Represents the options for the LLM.\n */\nexport interface LLMOptions {\n model?: LLMModel;\n temperature?: number;\n top_p?: number;\n frequency_penalty?: number;\n presence_penalty?: number;\n max_completion_tokens?: number;\n tools?: ChatCompletionTool[];\n developerPrompt?: string;\n context?: ChatCompletionMessageParam[];\n store?: boolean;\n reasoning_effort?: 'none' | 'minimal' | 'low' | 'medium' | 'high' | 'xhigh' | 'max';\n reasoning_mode?: 'standard' | 'pro';\n reasoning_context?: 'auto' | 'current_turn' | 'all_turns';\n metadata?: Record<string, string>;\n parallel_tool_calls?: boolean;\n service_tier?: 'auto' | 'default' | 'flex' | 'priority';\n apiKey?: string;\n}\n\n/**\n * Represents the response from the LLM.\n */\nexport interface LLMResponse<T> {\n response: T;\n usage: LLMUsage;\n tool_calls?: ChatCompletionMessageToolCall[];\n}\n\n/**\n * Represents the format of the OpenAI response.\n */\nexport type OpenAIResponseFormat = 'text' | 'json' | ResponseFormatTextJSONSchemaConfig;\n\n/**\n * Represents schema input for structured outputs in OpenAI calls.\n * Can be either a JSON Schema object or a Zod schema.\n */\nexport type OpenAISchemaInput = ResponseFormatTextJSONSchemaConfig['schema'] | ZodType;\n\n/**\n * Supported image detail levels for OpenAI Responses vision inputs.\n */\nexport type OpenAIImageDetail = ResponseInputImage['detail'];\n\n/**\n * A remote image URL to analyze.\n */\nexport interface OpenAIImageURLInput {\n url: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * A base64-encoded image to analyze.\n * If `base64` is a raw base64 string, `mimeType` is used to create a data URL.\n */\nexport interface OpenAIImageBase64Input {\n base64: string;\n mimeType?: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * A fully formed data URL to analyze.\n */\nexport interface OpenAIImageDataURLInput {\n dataUrl: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * An already-uploaded OpenAI file ID to analyze.\n */\nexport interface OpenAIImageFileIDInput {\n fileId: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * A local file path to upload for vision analysis in Node.js environments.\n */\nexport interface OpenAIImageFilePathInput {\n filePath: string;\n filename?: string;\n mimeType?: string;\n detail?: OpenAIImageDetail;\n}\n\n/**\n * Vision image input accepted by the OpenAI Responses helper.\n */\nexport type OpenAIImageInput =\n | OpenAIImageURLInput\n | OpenAIImageBase64Input\n | OpenAIImageDataURLInput\n | OpenAIImageFileIDInput\n | OpenAIImageFilePathInput;\n\n/**\n * Represents the options for the OpenAI Images API.\n * Extends the official ImageGenerateParams but with more user-friendly option names.\n */\nexport interface ImageGenerationOptions {\n model?: DiscoImageModel;\n size?: ImageGenerateParams['size'];\n outputFormat?: 'jpeg' | 'png' | 'webp';\n compression?: number;\n quality?: ImageGenerateParams['quality'];\n count?: number | null;\n apiKey?: string;\n background?: ImageGenerateParams['background'];\n moderation?: ImageGenerateParams['moderation'];\n /**\n * Optional multimodal LLM to pair with image outputs (e.g., gpt-5.4).\n */\n visionModel?: LLMModel;\n}\n\nexport type DiscoImageModel = OpenAIImageModel;\n\n/**\n * Context message for conversation history\n */\nexport interface ContextMessage {\n role: 'user' | 'assistant' | 'system' | 'developer';\n content: string;\n}\n\n\n// Re-export OpenAI types for convenience\nexport type { ImageModel, ImageGenerateParams } from 'openai/resources/images';\nexport type { ImagesResponse, Image } from 'openai/resources/images';\nexport type { Tool } from 'openai/resources/responses/responses';\n", "// llm-openai.ts\n\nimport OpenAI from 'openai';\nimport { zodTextFormat } from 'openai/helpers/zod';\nimport type { ZodType } from 'zod';\n\nimport type {\n Tool,\n ResponseInput,\n EasyInputMessage,\n ResponseInputImage,\n ResponseInputText,\n} from 'openai/resources/responses/responses';\n\nimport { calculateCost, DEFAULT_MODEL } from './llm-config';\nimport { parseResponse, normalizeModelName } from './llm-utils';\nimport { isOpenAIModel } from './types';\nimport type {\n LLMResponse,\n LLMOptions,\n LLMModel,\n OpenAIResponseFormat,\n ContextMessage,\n OpenAISchemaInput,\n OpenAIImageInput,\n OpenAIImageDetail,\n} from './types';\nimport type {\n ResponseCreateParamsNonStreaming,\n ResponseOutputItem,\n ResponseFunctionToolCall,\n ResponseCodeInterpreterToolCall,\n ResponseOutputMessage,\n ResponseOutputText,\n ResponseFormatTextJSONSchemaConfig,\n} from 'openai/resources/responses/responses';\n\nexport const DEFAULT_OPTIONS: LLMOptions = {\n model: DEFAULT_MODEL,\n parallel_tool_calls: false,\n};\n\nconst DEFAULT_IMAGE_MIME_TYPE = 'image/webp';\n\n/**\n * Checks if the given direct OpenAI model supports the temperature parameter.\n * @param model The model to check.\n * @returns True if the model supports the temperature parameter, false otherwise.\n */\nexport function supportsTemperature(_model: string): boolean {\n return false;\n}\n\nfunction isZodSchema(schema: OpenAISchemaInput): schema is ZodType {\n return typeof schema === 'object' && schema !== null && 'safeParse' in schema;\n}\n\nfunction buildJsonSchemaFormat(\n schema: OpenAISchemaInput,\n schemaName: string,\n schemaDescription?: string,\n schemaStrict?: boolean\n): ResponseFormatTextJSONSchemaConfig {\n if (isZodSchema(schema)) {\n const zodFormat = zodTextFormat(\n schema,\n schemaName,\n schemaDescription\n ? {\n description: schemaDescription,\n }\n : undefined\n );\n\n return {\n type: 'json_schema',\n name: zodFormat.name,\n schema: zodFormat.schema,\n ...(zodFormat.description ? { description: zodFormat.description } : {}),\n ...(schemaStrict !== undefined ? { strict: schemaStrict } : { strict: zodFormat.strict }),\n };\n }\n\n return {\n type: 'json_schema',\n name: schemaName,\n schema,\n ...(schemaDescription ? { description: schemaDescription } : {}),\n ...(schemaStrict !== undefined ? { strict: schemaStrict } : {}),\n };\n}\n\nfunction resolveOpenAIApiKey(apiKey?: string): string {\n const resolvedApiKey = apiKey || process.env.OPENAI_API_KEY;\n\n if (!resolvedApiKey) {\n throw new Error('OpenAI API key is not provided and OPENAI_API_KEY environment variable is not set');\n }\n\n return resolvedApiKey;\n}\n\nfunction createOpenAIClient(apiKey: string): OpenAI {\n return new OpenAI({\n apiKey,\n });\n}\n\nfunction normalizeImageDataUrl(imageData: string, mimeType = DEFAULT_IMAGE_MIME_TYPE): string {\n return imageData.startsWith('data:') ? imageData : `data:${mimeType};base64,${imageData}`;\n}\n\nfunction getFilenameFromPath(filePath: string): string {\n const normalizedPath = filePath.replace(/\\\\/g, '/');\n const pathSegments = normalizedPath.split('/');\n const filename = pathSegments[pathSegments.length - 1];\n\n if (!filename) {\n throw new Error(`Could not determine a filename from file path: ${filePath}`);\n }\n\n return filename;\n}\n\nfunction inferImageMimeType(filePath: string): string | undefined {\n const normalizedPath = filePath.toLowerCase();\n\n if (normalizedPath.endsWith('.png')) {\n return 'image/png';\n }\n\n if (normalizedPath.endsWith('.jpg') || normalizedPath.endsWith('.jpeg')) {\n return 'image/jpeg';\n }\n\n if (normalizedPath.endsWith('.webp')) {\n return 'image/webp';\n }\n\n if (normalizedPath.endsWith('.gif')) {\n return 'image/gif';\n }\n\n return undefined;\n}\n\nasync function readLocalFileBytes(filePath: string): Promise<Uint8Array> {\n try {\n const dynamicImport = new Function('specifier', 'return import(specifier);') as (\n specifier: string\n ) => Promise<{ readFile: (path: string) => Promise<Uint8Array> }>;\n const { readFile } = await dynamicImport('node:fs/promises');\n\n return await readFile(filePath);\n } catch {\n throw new Error('Local image file uploads require a Node.js runtime with access to node:fs/promises');\n }\n}\n\nasync function uploadVisionFileFromPath(\n openai: OpenAI,\n filePath: string,\n filename?: string,\n mimeType?: string\n): Promise<string> {\n const fileBytes = await readLocalFileBytes(filePath);\n const resolvedFilename = filename || getFilenameFromPath(filePath);\n const resolvedMimeType = mimeType || inferImageMimeType(filePath);\n const uploadableFile = await OpenAI.toFile(\n fileBytes,\n resolvedFilename,\n resolvedMimeType ? { type: resolvedMimeType } : undefined\n );\n\n const uploadedFile = await openai.files.create({\n file: uploadableFile,\n purpose: 'vision',\n });\n\n return uploadedFile.id;\n}\n\nfunction collectImageInputs(\n image: OpenAIImageInput | undefined,\n images: OpenAIImageInput[] | undefined,\n imageBase64: string | undefined\n): OpenAIImageInput[] {\n const collectedImages: OpenAIImageInput[] = [];\n\n if (image) {\n collectedImages.push(image);\n }\n\n if (images && images.length > 0) {\n collectedImages.push(...images);\n }\n\n if (imageBase64) {\n collectedImages.push({ base64: imageBase64 });\n }\n\n return collectedImages;\n}\n\nfunction hasLocalFileImage(images: OpenAIImageInput[]): boolean {\n return images.some((image) => 'filePath' in image);\n}\n\nasync function buildImageContentPart(\n image: OpenAIImageInput,\n defaultDetail: OpenAIImageDetail,\n openai?: OpenAI\n): Promise<ResponseInputImage> {\n const detail = image.detail ?? defaultDetail;\n\n if ('url' in image) {\n return {\n type: 'input_image',\n detail,\n image_url: image.url,\n };\n }\n\n if ('dataUrl' in image) {\n return {\n type: 'input_image',\n detail,\n image_url: image.dataUrl,\n };\n }\n\n if ('base64' in image) {\n return {\n type: 'input_image',\n detail,\n image_url: normalizeImageDataUrl(image.base64, image.mimeType),\n };\n }\n\n if ('fileId' in image) {\n return {\n type: 'input_image',\n detail,\n file_id: image.fileId,\n };\n }\n\n if (!openai) {\n throw new Error('A local image file path was provided, but no OpenAI client is available to upload it');\n }\n\n const fileId = await uploadVisionFileFromPath(openai, image.filePath, image.filename, image.mimeType);\n return {\n type: 'input_image',\n detail,\n file_id: fileId,\n };\n}\n\nasync function buildPromptContent(\n input: string,\n imageInputs: OpenAIImageInput[],\n imageDetail: OpenAIImageDetail,\n openai?: OpenAI\n): Promise<string | Array<ResponseInputText | ResponseInputImage>> {\n if (imageInputs.length === 0) {\n return input;\n }\n\n const imageContent = await Promise.all(imageInputs.map((image) => buildImageContentPart(image, imageDetail, openai)));\n\n return [{ type: 'input_text', text: input }, ...imageContent];\n}\n\nexport async function uploadVisionFile(\n filePath: string,\n options: {\n apiKey?: string;\n filename?: string;\n mimeType?: string;\n } = {}\n): Promise<string> {\n const resolvedApiKey = resolveOpenAIApiKey(options.apiKey);\n const openai = createOpenAIClient(resolvedApiKey);\n\n return await uploadVisionFileFromPath(openai, filePath, options.filename, options.mimeType);\n}\n\n/**\n * Makes a call to OpenAI's Responses API for more advanced use cases with built-in tools.\n *\n * This function provides access to the Responses API which supports:\n * - Built-in tools (web search, file search, computer use, code interpreter, image generation)\n * - Background processing\n * - Conversation state management\n * - GPT-5 reasoning controls\n *\n * @example\n * // Basic text response\n * const response = await makeResponsesAPICall('What is the weather like?');\n *\n * @example\n * // With web search tool\n * const response = await makeResponsesAPICall('Latest news about AI', {\n * tools: [{ type: 'web_search_preview' }]\n * });\n *\n * @param input - The input content. Can be:\n * - A string for simple text prompts\n * - An array of input items for complex/multi-modal content\n * @param options - Configuration options for the Responses API\n * @returns Promise<LLMResponse<T>> - The response in the same format as makeLLMCall\n * @throws Error if the API call fails\n */\nexport const makeResponsesAPICall = async <T = string>(\n input: string | ResponseCreateParamsNonStreaming['input'],\n options: Omit<ResponseCreateParamsNonStreaming, 'input' | 'model'> & {\n apiKey?: string;\n model?: string;\n } = {}\n): Promise<LLMResponse<T>> => {\n const normalizedModel = normalizeModelName(options.model || DEFAULT_MODEL);\n if (!isOpenAIModel(normalizedModel)) {\n throw new Error(`Unsupported OpenAI model: ${normalizedModel}. Please use a supported GPT-5 model.`);\n }\n\n const apiKey = resolveOpenAIApiKey(options.apiKey);\n const openai = createOpenAIClient(apiKey);\n\n // Remove apiKey from options before creating request body\n const { apiKey: _, model: __, ...cleanOptions } = options;\n\n const requestBody: ResponseCreateParamsNonStreaming = {\n model: normalizedModel,\n input,\n ...cleanOptions,\n };\n\n // Make the API call to the Responses endpoint\n const response = await openai.responses.create(requestBody);\n const cacheHitTokens = response.usage?.input_tokens_details?.cached_tokens || 0;\n const cacheWriteTokens = response.usage?.input_tokens_details?.cache_write_tokens || 0;\n\n // Extract tool calls from the output\n const toolCalls = response.output\n ?.filter((item: ResponseOutputItem): item is ResponseFunctionToolCall => item.type === 'function_call')\n .map((toolCall: ResponseFunctionToolCall) => ({\n id: toolCall.call_id,\n type: 'function' as const,\n function: {\n name: toolCall.name,\n arguments: toolCall.arguments,\n },\n }));\n\n // Extract code interpreter outputs if present\n const codeInterpreterCalls = response.output?.filter(\n (item: ResponseOutputItem): item is ResponseCodeInterpreterToolCall => item.type === 'code_interpreter_call'\n );\n let codeInterpreterOutputs: ResponseCodeInterpreterToolCall['outputs'] | undefined = undefined;\n if (codeInterpreterCalls && codeInterpreterCalls.length > 0) {\n // Each code_interpreter_call has an 'outputs' array property\n codeInterpreterOutputs = codeInterpreterCalls.flatMap((ci) => {\n // Return outputs if present, otherwise empty array\n if (ci.outputs) return ci.outputs;\n return [];\n });\n }\n\n // Handle tool calls differently\n if (toolCalls && toolCalls.length > 0) {\n return {\n response: {\n tool_calls: toolCalls.map((tc) => ({\n id: tc.id,\n name: tc.function.name,\n arguments: JSON.parse(tc.function.arguments),\n })),\n } as T,\n usage: {\n prompt_tokens: response.usage?.input_tokens || 0,\n completion_tokens: response.usage?.output_tokens || 0,\n reasoning_tokens: response.usage?.output_tokens_details?.reasoning_tokens || 0,\n provider: 'openai',\n model: normalizedModel,\n cache_hit_tokens: cacheHitTokens,\n cache_write_tokens: cacheWriteTokens,\n cost: calculateCost(\n 'openai',\n normalizedModel,\n response.usage?.input_tokens || 0,\n response.usage?.output_tokens || 0,\n response.usage?.output_tokens_details?.reasoning_tokens || 0,\n cacheHitTokens,\n cacheWriteTokens\n ),\n },\n tool_calls: toolCalls,\n ...(codeInterpreterOutputs ? { code_interpreter_outputs: codeInterpreterOutputs } : {}),\n };\n }\n\n // Extract text content from the response output\n const textContent =\n response.output\n ?.filter((item: ResponseOutputItem): item is ResponseOutputMessage => item.type === 'message')\n .map((item: ResponseOutputMessage) =>\n item.content\n .filter((content): content is ResponseOutputText => content.type === 'output_text')\n .map((content) => content.text)\n .join('')\n )\n .join('') || '';\n\n // Determine the format for parsing the response\n let parsingFormat: OpenAIResponseFormat = 'text';\n const requestedFormat = requestBody.text?.format;\n if (requestedFormat?.type === 'json_object') {\n parsingFormat = 'json';\n } else if (requestedFormat?.type === 'json_schema') {\n parsingFormat = requestedFormat;\n }\n\n // Handle regular responses\n const parsedResponse = await parseResponse<T>(textContent, parsingFormat);\n if (parsedResponse === null) {\n throw new Error('Failed to parse response from Responses API');\n }\n\n return {\n response: parsedResponse,\n usage: {\n prompt_tokens: response.usage?.input_tokens || 0,\n completion_tokens: response.usage?.output_tokens || 0,\n reasoning_tokens: response.usage?.output_tokens_details?.reasoning_tokens || 0,\n provider: 'openai',\n model: normalizedModel,\n cache_hit_tokens: cacheHitTokens,\n cache_write_tokens: cacheWriteTokens,\n cost: calculateCost(\n 'openai',\n normalizedModel,\n response.usage?.input_tokens || 0,\n response.usage?.output_tokens || 0,\n response.usage?.output_tokens_details?.reasoning_tokens || 0,\n cacheHitTokens,\n cacheWriteTokens\n ),\n },\n tool_calls: toolCalls,\n ...(codeInterpreterOutputs ? { code_interpreter_outputs: codeInterpreterOutputs } : {}),\n };\n};\n\n/**\n * Makes a call to the OpenAI Responses API for advanced use cases with built-in tools.\n *\n * @param input The text prompt to send to the model (e.g., \"What's in this image?\")\n * @param options The options for the Responses API call, including optional image data and context.\n * @return A promise that resolves to the response from the Responses API.\n *\n * @example\n * // With conversation context\n * const response = await makeLLMCall(\"What did I ask about earlier?\", {\n * context: [\n * { role: 'user', content: 'What is the capital of France?' },\n * { role: 'assistant', content: 'The capital of France is Paris.' }\n * ]\n * });\n */\nexport async function makeLLMCall<T = string>(\n input: string,\n options: {\n apiKey?: string;\n model?: LLMModel;\n responseFormat?: OpenAIResponseFormat;\n schema?: OpenAISchemaInput;\n schemaName?: string;\n schemaDescription?: string;\n schemaStrict?: boolean;\n tools?: Tool[];\n useCodeInterpreter?: boolean;\n useWebSearch?: boolean;\n image?: OpenAIImageInput;\n images?: OpenAIImageInput[];\n imageBase64?: string;\n imageDetail?: OpenAIImageDetail;\n context?: ContextMessage[];\n reasoningEffort?: LLMOptions['reasoning_effort'];\n reasoningMode?: LLMOptions['reasoning_mode'];\n reasoningContext?: LLMOptions['reasoning_context'];\n } = {}\n): Promise<LLMResponse<T>> {\n const {\n apiKey,\n model = DEFAULT_MODEL,\n responseFormat = 'text',\n schema,\n schemaName = 'response',\n schemaDescription,\n schemaStrict,\n tools,\n useCodeInterpreter = false,\n useWebSearch = false,\n image,\n images,\n imageBase64,\n imageDetail = 'high',\n context,\n reasoningEffort,\n reasoningMode,\n reasoningContext,\n } = options;\n\n // Validate model\n const normalizedModel = normalizeModelName(model);\n if (!isOpenAIModel(normalizedModel)) {\n throw new Error(`Unsupported OpenAI model: ${normalizedModel}. Please use a supported GPT-5 model.`);\n }\n\n const resolvedApiKey = resolveOpenAIApiKey(apiKey);\n const imageInputs = collectImageInputs(image, images, imageBase64);\n const openai = hasLocalFileImage(imageInputs) ? createOpenAIClient(resolvedApiKey) : undefined;\n const promptContent = await buildPromptContent(input, imageInputs, imageDetail, openai);\n\n // Process input for conversation context and image analysis\n let processedInput: string | ResponseInput;\n\n if (context && context.length > 0) {\n // Build conversation array with context\n const conversationMessages: EasyInputMessage[] = [];\n\n // Add context messages\n for (const contextMsg of context) {\n conversationMessages.push({\n role: contextMsg.role,\n content: contextMsg.content,\n type: 'message',\n });\n }\n\n // Add current input message\n if (imageInputs.length > 0) {\n // Current message includes text and one or more images\n conversationMessages.push({\n role: 'user',\n content: promptContent,\n type: 'message',\n });\n } else {\n // Current message is just text\n conversationMessages.push({\n role: 'user',\n content: input,\n type: 'message',\n });\n }\n\n processedInput = conversationMessages;\n } else if (imageInputs.length > 0) {\n // No context, but has image(s)\n processedInput = [\n {\n role: 'user',\n content: promptContent,\n type: 'message',\n },\n ];\n } else {\n // No context, no image - simple string input\n processedInput = input;\n }\n\n // Build the options object for makeResponsesAPICall\n let responsesOptions: Parameters<typeof makeResponsesAPICall>[1] = {\n apiKey: resolvedApiKey,\n model: normalizedModel,\n parallel_tool_calls: false,\n tools,\n };\n\n // Only include temperature if the model supports it\n if (supportsTemperature(normalizedModel)) {\n responsesOptions.temperature = 0.2;\n }\n\n if (reasoningEffort || reasoningMode || reasoningContext) {\n responsesOptions.reasoning = {\n ...(reasoningEffort ? { effort: reasoningEffort } : {}),\n ...(reasoningMode ? { mode: reasoningMode } : {}),\n ...(reasoningContext ? { context: reasoningContext } : {}),\n };\n }\n\n // Configure response format\n if (schema) {\n responsesOptions.text = {\n format: buildJsonSchemaFormat(schema, schemaName, schemaDescription, schemaStrict),\n };\n } else if (responseFormat === 'json') {\n responsesOptions.text = { format: { type: 'json_object' } };\n } else if (typeof responseFormat === 'object' && responseFormat.type === 'json_schema') {\n responsesOptions.text = { format: responseFormat };\n }\n\n // Configure built-in tools\n if (useCodeInterpreter) {\n responsesOptions.tools = [{ type: 'code_interpreter', container: { type: 'auto' } }];\n responsesOptions.include = ['code_interpreter_call.outputs'];\n }\n\n if (useWebSearch) {\n responsesOptions.tools = [{ type: 'web_search_preview' }];\n }\n\n return await makeResponsesAPICall<T>(processedInput, responsesOptions);\n}\n", "// llm-openai-config.ts\nimport type { ImageGenerateParams } from 'openai/resources/images';\nimport type { OpenAIImageModel, OpenAIModel } from './types/llm-types';\n\nexport const DEFAULT_MODEL: OpenAIModel = 'gpt-5.6-luna';\n\nexport const DEFAULT_DEVELOPER_PROMPT = `\n You are a highly experienced coding, business analyst, and financial analyst associate.\n Help with coding, business process design and analysis, data generation and refinement, content creation, financial analysis, and more.\n When presented with a coding problem, logic problem, or other problem benefiting from systematic thinking, think through it step by step before giving your final answer.\n Present complete, high-confidence, final answers only. Do not rephrase to be more brief or omit parts of answers.\n Respond only with final content (e.g. code, a json or yaml object, a formatted string, or a markdown document) and nothing else. Do not reply with a preamble, introduction, or conclusion.\n`;\n\ninterface AIModelCosts {\n [modelName: string]: {\n inputCost: number;\n outputCost: number;\n cacheHitCost?: number;\n cacheWriteCost?: number;\n };\n}\n\nconst GPT_5_HIGH_CONTEXT_THRESHOLD_TOKENS = 272_000;\nconst GPT_5_HIGH_CONTEXT_INPUT_MULTIPLIER = 2;\nconst GPT_5_HIGH_CONTEXT_OUTPUT_MULTIPLIER = 1.5;\n\n/** Token costs in USD per 1M tokens. Last updated July 2026 from the OpenAI API pricing page. */\nexport const openAiModelCosts: AIModelCosts = {\n 'gpt-5.6': {\n inputCost: 5 / 1_000_000,\n cacheHitCost: 0.5 / 1_000_000,\n cacheWriteCost: 6.25 / 1_000_000,\n outputCost: 30 / 1_000_000,\n },\n 'gpt-5.6-sol': {\n inputCost: 5 / 1_000_000,\n cacheHitCost: 0.5 / 1_000_000,\n cacheWriteCost: 6.25 / 1_000_000,\n outputCost: 30 / 1_000_000,\n },\n 'gpt-5.6-terra': {\n inputCost: 2.5 / 1_000_000,\n cacheHitCost: 0.25 / 1_000_000,\n cacheWriteCost: 3.125 / 1_000_000,\n outputCost: 15 / 1_000_000,\n },\n 'gpt-5.6-luna': {\n inputCost: 1 / 1_000_000,\n cacheHitCost: 0.1 / 1_000_000,\n cacheWriteCost: 1.25 / 1_000_000,\n outputCost: 6 / 1_000_000,\n },\n 'gpt-5': {\n inputCost: 1.25 / 1_000_000,\n cacheHitCost: 0.125 / 1_000_000,\n outputCost: 10 / 1_000_000,\n },\n 'gpt-5-mini': {\n inputCost: 0.25 / 1_000_000,\n cacheHitCost: 0.025 / 1_000_000,\n outputCost: 2 / 1_000_000,\n },\n 'gpt-5.4-mini': {\n inputCost: 0.75 / 1_000_000,\n cacheHitCost: 0.075 / 1_000_000,\n outputCost: 4.5 / 1_000_000,\n },\n 'gpt-5.4-nano': {\n inputCost: 0.2 / 1_000_000,\n cacheHitCost: 0.02 / 1_000_000,\n outputCost: 1.25 / 1_000_000,\n },\n 'gpt-5-nano': {\n inputCost: 0.05 / 1_000_000,\n cacheHitCost: 0.005 / 1_000_000,\n outputCost: 0.4 / 1_000_000,\n },\n 'gpt-5.1': {\n inputCost: 1.25 / 1_000_000,\n cacheHitCost: 0.125 / 1_000_000,\n outputCost: 10 / 1_000_000,\n },\n 'gpt-5.4': {\n inputCost: 2.5 / 1_000_000,\n cacheHitCost: 0.25 / 1_000_000,\n outputCost: 15 / 1_000_000,\n },\n 'gpt-5.5': {\n inputCost: 5 / 1_000_000,\n cacheHitCost: 0.5 / 1_000_000,\n outputCost: 30 / 1_000_000,\n },\n 'gpt-5.5-pro': {\n inputCost: 30 / 1_000_000,\n outputCost: 180 / 1_000_000,\n },\n 'gpt-5.2': {\n inputCost: 1.75 / 1_000_000,\n cacheHitCost: 0.175 / 1_000_000,\n outputCost: 14 / 1_000_000,\n },\n 'gpt-5.2-pro': {\n inputCost: 21 / 1_000_000,\n outputCost: 168 / 1_000_000,\n },\n 'gpt-5.1-codex': {\n inputCost: 1.25 / 1_000_000,\n cacheHitCost: 0.125 / 1_000_000,\n outputCost: 10 / 1_000_000,\n },\n 'gpt-5.1-codex-max': {\n inputCost: 1.25 / 1_000_000,\n cacheHitCost: 0.125 / 1_000_000,\n outputCost: 10 / 1_000_000,\n },\n};\n\nexport const deepseekModelCosts: AIModelCosts = {\n 'deepseek-chat': {\n inputCost: 0.27 / 1_000_000, // $0.27 per 1M tokens (Cache miss price)\n cacheHitCost: 0.07 / 1_000_000, // $0.07 per 1M tokens (Cache hit price)\n outputCost: 1.1 / 1_000_000, // $1.10 per 1M tokens\n },\n 'deepseek-reasoner': {\n inputCost: 0.55 / 1_000_000, // $0.55 per 1M tokens (Cache miss price)\n cacheHitCost: 0.14 / 1_000_000, // $0.14 per 1M tokens (Cache hit price)\n outputCost: 2.19 / 1_000_000, // $2.19 per 1M tokens\n },\n};\n\nfunction shouldUseGPT5HighContextPricing(model: string, inputTokens: number): boolean {\n return (\n (model === 'gpt-5.4' || model === 'gpt-5.5' || model === 'gpt-5.6' || model === 'gpt-5.6-sol' || model === 'gpt-5.6-terra' || model === 'gpt-5.6-luna') &&\n inputTokens > GPT_5_HIGH_CONTEXT_THRESHOLD_TOKENS\n );\n}\n\nexport type PricedOpenAIImageModel =\n | 'gpt-image-2'\n | 'gpt-image-2-2026-04-21'\n | 'gpt-image-1.5'\n | 'gpt-image-1'\n | 'gpt-image-1-mini';\nexport type OpenAIImagePricingQuality = 'low' | 'medium' | 'high';\nexport type OpenAIImagePricingSize = '1024x1024' | '1024x1536' | '1536x1024';\n\nexport const DEFAULT_IMAGE_PRICING_QUALITY: OpenAIImagePricingQuality = 'high';\nexport const DEFAULT_IMAGE_PRICING_SIZE: OpenAIImagePricingSize = '1024x1024';\n\nconst PRICED_OPENAI_IMAGE_MODELS: readonly PricedOpenAIImageModel[] = [\n 'gpt-image-2',\n 'gpt-image-2-2026-04-21',\n 'gpt-image-1.5',\n 'gpt-image-1',\n 'gpt-image-1-mini',\n];\nconst OPENAI_IMAGE_PRICING_SIZES: readonly OpenAIImagePricingSize[] = ['1024x1024', '1024x1536', '1536x1024'];\n\n/**\n * Estimated image output costs in USD per image for common GPT Image sizes.\n * Last updated May 2026 from the OpenAI image generation guide. Text and image\n * input token costs for prompts and edit inputs are not included.\n */\nexport const openAiImageCostByQualityAndSize: Record<\n PricedOpenAIImageModel,\n Record<OpenAIImagePricingQuality, Record<OpenAIImagePricingSize, number>>\n> = {\n 'gpt-image-2': {\n low: {\n '1024x1024': 0.006,\n '1024x1536': 0.005,\n '1536x1024': 0.005,\n },\n medium: {\n '1024x1024': 0.053,\n '1024x1536': 0.041,\n '1536x1024': 0.041,\n },\n high: {\n '1024x1024': 0.211,\n '1024x1536': 0.165,\n '1536x1024': 0.165,\n },\n },\n 'gpt-image-2-2026-04-21': {\n low: {\n '1024x1024': 0.006,\n '1024x1536': 0.005,\n '1536x1024': 0.005,\n },\n medium: {\n '1024x1024': 0.053,\n '1024x1536': 0.041,\n '1536x1024': 0.041,\n },\n high: {\n '1024x1024': 0.211,\n '1024x1536': 0.165,\n '1536x1024': 0.165,\n },\n },\n 'gpt-image-1.5': {\n low: {\n '1024x1024': 0.009,\n '1024x1536': 0.013,\n '1536x1024': 0.013,\n },\n medium: {\n '1024x1024': 0.034,\n '1024x1536': 0.05,\n '1536x1024': 0.05,\n },\n high: {\n '1024x1024': 0.133,\n '1024x1536': 0.2,\n '1536x1024': 0.2,\n },\n },\n 'gpt-image-1': {\n low: {\n '1024x1024': 0.011,\n '1024x1536': 0.016,\n '1536x1024': 0.016,\n },\n medium: {\n '1024x1024': 0.042,\n '1024x1536': 0.063,\n '1536x1024': 0.063,\n },\n high: {\n '1024x1024': 0.167,\n '1024x1536': 0.25,\n '1536x1024': 0.25,\n },\n },\n 'gpt-image-1-mini': {\n low: {\n '1024x1024': 0.005,\n '1024x1536': 0.006,\n '1536x1024': 0.006,\n },\n medium: {\n '1024x1024': 0.011,\n '1024x1536': 0.015,\n '1536x1024': 0.015,\n },\n high: {\n '1024x1024': 0.036,\n '1024x1536': 0.052,\n '1536x1024': 0.052,\n },\n },\n};\n\n/** Default image output costs in USD per image for legacy callers. */\nexport const openAiImageCosts: Record<PricedOpenAIImageModel, number> = {\n 'gpt-image-2':\n openAiImageCostByQualityAndSize['gpt-image-2'][DEFAULT_IMAGE_PRICING_QUALITY][DEFAULT_IMAGE_PRICING_SIZE],\n 'gpt-image-2-2026-04-21':\n openAiImageCostByQualityAndSize['gpt-image-2-2026-04-21'][DEFAULT_IMAGE_PRICING_QUALITY][\n DEFAULT_IMAGE_PRICING_SIZE\n ],\n 'gpt-image-1.5':\n openAiImageCostByQualityAndSize['gpt-image-1.5'][DEFAULT_IMAGE_PRICING_QUALITY][DEFAULT_IMAGE_PRICING_SIZE],\n 'gpt-image-1':\n openAiImageCostByQualityAndSize['gpt-image-1'][DEFAULT_IMAGE_PRICING_QUALITY][DEFAULT_IMAGE_PRICING_SIZE],\n 'gpt-image-1-mini':\n openAiImageCostByQualityAndSize['gpt-image-1-mini'][DEFAULT_IMAGE_PRICING_QUALITY][DEFAULT_IMAGE_PRICING_SIZE],\n};\n\nfunction isPricedOpenAIImageModel(model: string): model is PricedOpenAIImageModel {\n return PRICED_OPENAI_IMAGE_MODELS.includes(model as PricedOpenAIImageModel);\n}\n\nfunction isOpenAIImagePricingSize(size: string): size is OpenAIImagePricingSize {\n return OPENAI_IMAGE_PRICING_SIZES.includes(size as OpenAIImagePricingSize);\n}\n\nfunction resolveImagePricingQuality(quality?: ImageGenerateParams['quality']): OpenAIImagePricingQuality {\n if (quality === 'low' || quality === 'medium' || quality === 'high') {\n return quality;\n }\n\n return DEFAULT_IMAGE_PRICING_QUALITY;\n}\n\nfunction resolveImagePricingSize(size?: ImageGenerateParams['size']): OpenAIImagePricingSize {\n if (typeof size === 'string' && isOpenAIImagePricingSize(size)) {\n return size;\n }\n\n return DEFAULT_IMAGE_PRICING_SIZE;\n}\n\n/**\n * Calculates the cost of generating images using OpenAI's Images API.\n *\n * @param model The image generation model name.\n * @param imageCount The number of images generated.\n * @param quality The requested image quality.\n * @param size The requested image size.\n * @returns The cost of generating the images in USD.\n */\nexport function calculateImageCost(\n model: OpenAIImageModel | string,\n imageCount: number,\n quality?: ImageGenerateParams['quality'],\n size?: ImageGenerateParams['size']\n): number {\n if (typeof model !== 'string' || typeof imageCount !== 'number' || imageCount <= 0) {\n return 0;\n }\n\n if (!isPricedOpenAIImageModel(model)) return 0;\n\n const pricingQuality = resolveImagePricingQuality(quality);\n const pricingSize = resolveImagePricingSize(size);\n const costPerImage = openAiImageCostByQualityAndSize[model][pricingQuality][pricingSize];\n\n return imageCount * costPerImage;\n}\n\n/**\n * Calculates the cost of calling a language model in USD based on the provider and model, tokens, and given costs per 1M tokens.\n *\n * @param provider The provider of the language model. Supported providers are 'openai' and 'deepseek'.\n * @param model The name of the language model. Supported models are listed in the `openAiModelCosts` and `deepseekModelCosts` objects.\n * @param inputTokens The number of input tokens passed to the language model.\n * @param outputTokens The number of output tokens generated by the language model.\n * @param reasoningTokens The number of output tokens generated by the language model for reasoning.\n * @param cacheHitTokens The number of input tokens billed at cached-input rates.\n * @param cacheWriteTokens The number of input tokens billed at cache-write rates.\n * @returns The cost of calling the language model in USD.\n */\nexport function calculateCost(\n provider: string,\n model: string,\n inputTokens: number,\n outputTokens: number,\n reasoningTokens?: number,\n cacheHitTokens?: number,\n cacheWriteTokens?: number\n): number {\n if (\n typeof provider !== 'string' ||\n typeof model !== 'string' ||\n typeof inputTokens !== 'number' ||\n typeof outputTokens !== 'number' ||\n (reasoningTokens !== undefined && typeof reasoningTokens !== 'number') ||\n (cacheHitTokens !== undefined && typeof cacheHitTokens !== 'number') ||\n (cacheWriteTokens !== undefined && typeof cacheWriteTokens !== 'number')\n ) {\n return 0;\n }\n\n const modelCosts = provider === 'deepseek' ? deepseekModelCosts[model] : openAiModelCosts[model];\n\n if (!modelCosts) return 0;\n\n const boundedCacheHitTokens = Math.min(Math.max(cacheHitTokens || 0, 0), inputTokens);\n const boundedCacheWriteTokens = Math.min(Math.max(cacheWriteTokens || 0, 0), inputTokens - boundedCacheHitTokens);\n const uncachedInputTokens = inputTokens - boundedCacheHitTokens - boundedCacheWriteTokens;\n const inputCost =\n uncachedInputTokens * modelCosts.inputCost +\n boundedCacheHitTokens * (modelCosts.cacheHitCost || modelCosts.inputCost) +\n boundedCacheWriteTokens * (modelCosts.cacheWriteCost || modelCosts.inputCost);\n\n let outputCost = outputTokens * modelCosts.outputCost;\n let reasoningCost = (reasoningTokens || 0) * modelCosts.outputCost;\n\n if (provider === 'openai' && shouldUseGPT5HighContextPricing(model, inputTokens)) {\n return (\n inputCost * GPT_5_HIGH_CONTEXT_INPUT_MULTIPLIER +\n outputCost * GPT_5_HIGH_CONTEXT_OUTPUT_MULTIPLIER +\n reasoningCost * GPT_5_HIGH_CONTEXT_OUTPUT_MULTIPLIER\n );\n }\n\n return inputCost + outputCost + reasoningCost;\n}\n", "import OpenAI from 'openai';\nimport { DEFAULT_MODEL } from './llm-config';\n/**\n * Fix a broken JSON string by attempting to extract and parse valid JSON content. This function is very lenient and will attempt to fix many types of JSON errors, including unbalanced brackets, missing or extra commas, improperly escaped $ signs, unquoted strings, trailing commas, missing closing brackets or braces, etc.\n * @param {string} jsonStr - The broken JSON string to fix\n * @returns {JsonValue} - The parsed JSON value\n */\nexport function fixBrokenJson(jsonStr: string): JsonValue {\n // Pre-process: Fix improperly escaped $ signs\n jsonStr = jsonStr.replace(/\\\\\\$/g, '$');\n\n let index = 0;\n\n function parse(): JsonValue {\n const results: JsonValue[] = [];\n while (index < jsonStr.length) {\n skipWhitespace();\n const value = parseValue();\n if (value !== undefined) {\n results.push(value);\n } else {\n index++; // Skip invalid character\n }\n }\n return results.length === 1 ? results[0] : results;\n }\n\n function parseValue(): JsonValue | undefined {\n skipWhitespace();\n const char = getChar();\n if (!char) return undefined;\n if (char === '{') return parseObject();\n if (char === '[') return parseArray();\n if (char === '\"' || char === \"'\") return parseString();\n if (char === 't' && jsonStr.slice(index, index + 4).toLowerCase() === 'true') {\n index += 4;\n return true;\n }\n if (char === 'f' && jsonStr.slice(index, index + 5).toLowerCase() === 'false') {\n index += 5;\n return false;\n }\n if (char === 'n' && jsonStr.slice(index, index + 4).toLowerCase() === 'null') {\n index += 4;\n return null;\n }\n if (/[a-zA-Z]/.test(char)) return parseString(); // Unquoted string\n if (char === '-' || char === '.' || /\\d/.test(char)) return parseNumber();\n return undefined; // Unknown character\n }\n\n function parseObject(): JsonObject {\n const obj: JsonObject = {};\n index++; // Skip opening brace\n skipWhitespace();\n while (index < jsonStr.length && getChar() !== '}') {\n skipWhitespace();\n const key = parseString();\n if (key === undefined) {\n console.warn(`Expected key at position ${index}`);\n index++;\n continue;\n }\n skipWhitespace();\n if (getChar() === ':') {\n index++; // Skip colon\n } else {\n console.warn(`Missing colon after key \"${key}\" at position ${index}`);\n }\n skipWhitespace();\n const value = parseValue();\n if (value === undefined) {\n console.warn(`Expected value for key \"${key}\" at position ${index}`);\n index++;\n continue;\n }\n obj[key] = value;\n skipWhitespace();\n if (getChar() === ',') {\n index++; // Skip comma\n } else {\n break;\n }\n skipWhitespace();\n }\n if (getChar() === '}') {\n index++; // Skip closing brace\n } else {\n // Add a closing brace if it's missing\n jsonStr += '}';\n }\n return obj;\n }\n\n function parseArray(): JsonArray {\n const arr: JsonArray = [];\n index++; // Skip opening bracket\n skipWhitespace();\n while (index < jsonStr.length && getChar() !== ']') {\n const value = parseValue();\n if (value === undefined) {\n console.warn(`Expected value at position ${index}`);\n index++;\n } else {\n arr.push(value);\n }\n skipWhitespace();\n if (getChar() === ',') {\n index++; // Skip comma\n } else {\n break;\n }\n skipWhitespace();\n }\n if (getChar() === ']') {\n index++; // Skip closing bracket\n } else {\n console.warn(`Missing closing bracket for array at position ${index}`);\n }\n return arr;\n }\n\n function parseString(): string {\n const startChar = getChar();\n let result = '';\n let isQuoted = false;\n let delimiter = '';\n\n if (startChar === '\"' || startChar === \"'\") {\n isQuoted = true;\n delimiter = startChar;\n index++; // Skip opening quote\n }\n\n while (index < jsonStr.length) {\n const char = getChar();\n if (isQuoted) {\n if (char === delimiter) {\n index++; // Skip closing quote\n return result;\n } else if (char === '\\\\') {\n index++;\n const escapeChar = getChar();\n const escapeSequences: { [key: string]: string } = {\n n: '\\n',\n r: '\\r',\n t: '\\t',\n b: '\\b',\n f: '\\f',\n '\\\\': '\\\\',\n '/': '/',\n '\"': '\"',\n \"'\": \"'\",\n $: '$',\n };\n result += escapeSequences[escapeChar] || escapeChar;\n } else {\n result += char;\n }\n index++;\n } else {\n if (/\\s|,|}|]|\\:/.test(char)) {\n return result;\n } else {\n result += char;\n index++;\n }\n }\n }\n if (isQuoted) {\n console.warn(`Missing closing quote for string starting at position ${index}`);\n }\n return result;\n }\n\n function parseNumber(): number | undefined {\n const numberRegex = /^-?\\d+(\\.\\d+)?([eE][+-]?\\d+)?/;\n const match = numberRegex.exec(jsonStr.slice(index));\n if (match) {\n index += match[0].length;\n return parseFloat(match[0]);\n } else {\n console.warn(`Invalid number at position ${index}`);\n index++;\n return undefined;\n }\n }\n\n function getChar(): string {\n return jsonStr[index];\n }\n\n function skipWhitespace(): void {\n while (/\\s/.test(getChar())) index++;\n }\n\n try {\n return parse();\n } catch (error) {\n const msg = error instanceof Error ? error.message : String(error);\n console.error(`Error parsing JSON at position ${index}: ${msg}`);\n return null;\n }\n}\n\n/**\n * Returns true if the given JSON string is valid, false otherwise.\n *\n * This function simply attempts to parse the given string as JSON and returns true if successful, or false if an error is thrown.\n *\n * @param {string} jsonString The JSON string to validate.\n * @returns {boolean} True if the JSON string is valid, false otherwise.\n */\nexport function isValidJson(jsonString: string): boolean {\n try {\n JSON.parse(jsonString);\n return true;\n } catch {\n return false;\n }\n}\n\n// Types just for fixing JSON with AI\ninterface JsonObject {\n [key: string]: JsonValue;\n}\ntype JsonArray = JsonValue[];\ntype JsonValue = string | number | boolean | null | JsonObject | JsonArray;\n\nlet openai: OpenAI;\n\n/**\n * Initializes an instance of the OpenAI client, using the provided API key or the value of the OPENAI_API_KEY environment variable if no key is provided.\n * @param apiKey - the API key to use, or undefined to use the value of the OPENAI_API_KEY environment variable\n * @returns an instance of the OpenAI client\n * @throws an error if the API key is not provided and the OPENAI_API_KEY environment variable is not set\n */\nfunction initializeOpenAI(apiKey?: string): OpenAI {\n const key = apiKey || process.env.OPENAI_API_KEY;\n if (!key) {\n throw new Error('OpenAI API key is not provided and OPENAI_API_KEY environment variable is not set');\n }\n return new OpenAI({\n apiKey: key,\n defaultHeaders: { 'User-Agent': 'My Server-side Application (compatible; OpenAI API Client)' },\n });\n}\n\n/**\n * Fixes broken JSON by sending it to OpenAI to fix it.\n * If the model fails to return valid JSON, an error is thrown.\n * @param jsonStr - the broken JSON to fix\n * @param apiKey - the OpenAI API key to use, or undefined to use the value of the OPENAI_API_KEY environment variable\n * @returns the fixed JSON\n * @throws an error if the model fails to return valid JSON\n */\nexport async function fixJsonWithAI(jsonStr: string, apiKey?: string): Promise<JsonValue> {\n try {\n if (!openai) {\n openai = initializeOpenAI();\n }\n\n const completion = await openai.chat.completions.create({\n model: DEFAULT_MODEL,\n messages: [\n {\n role: 'system',\n content: 'You are a JSON fixer. Return only valid JSON without any additional text or explanation.',\n },\n {\n role: 'user',\n content: `Fix this broken JSON:\\n${jsonStr}`,\n },\n ],\n response_format: { type: 'json_object' },\n });\n\n const fixedJson = completion.choices[0]?.message?.content;\n\n if (fixedJson && isValidJson(fixedJson)) {\n return JSON.parse(fixedJson);\n }\n throw new Error('Failed to fix JSON with AI');\n } catch (err: unknown) {\n const errorMessage = err instanceof Error ? err.message : 'Unknown error occurred';\n throw new Error(`Error fixing JSON with AI: ${errorMessage}`);\n }\n}\n", "// llm-utils.ts\n\nimport { LLMModel, OpenAIModel, OpenAIResponseFormat } from './types';\nimport { fixBrokenJson, fixJsonWithAI } from './json-tools';\n\nexport function normalizeModelName(model: string): LLMModel {\n return model.replace(/_/g, '-').toLowerCase() as LLMModel;\n}\n\nexport const CODE_BLOCK_TYPES = ['javascript', 'js', 'graphql', 'json', 'typescript', 'python', 'markdown', 'yaml'];\n\n /**\n * Tries to parse JSON from the given content string according to the specified\n * response format. If the response format is 'json' or a JSON schema object, it\n * will attempt to parse the content using multiple strategies. If any of the\n * strategies succeed, it will return the parsed JSON object. If all of them fail,\n * it will throw an error.\n *\n * @param content The content string to parse\n * @param responseFormat The desired format of the response\n * @returns The parsed JSON object or null if it fails\n */\nexport async function parseResponse<T>(content: string, responseFormat: OpenAIResponseFormat): Promise<T | null> {\n if (!content) return null;\n\n if (responseFormat === 'json' || (typeof responseFormat === 'object' && responseFormat?.type === 'json_schema')) {\n let cleanedContent = content.trim();\n let detectedType: string | null = null;\n\n // Remove code block markers if present\n const startsWithCodeBlock = CODE_BLOCK_TYPES.some((type) => {\n if (cleanedContent.startsWith(`\\`\\`\\`${type}`)) {\n detectedType = type;\n return true;\n }\n return false;\n });\n\n if (startsWithCodeBlock && cleanedContent.endsWith('```')) {\n const firstLineEndIndex = cleanedContent.indexOf('\\n');\n if (firstLineEndIndex !== -1) {\n cleanedContent = cleanedContent.slice(firstLineEndIndex + 1, -3).trim();\n console.log(`Code block for type ${detectedType} detected and removed. Cleaned content: ${cleanedContent}`);\n }\n }\n\n // Multiple JSON parsing strategies\n const jsonParsingStrategies = [\n // Strategy 1: Direct parsing\n () => {\n try {\n return JSON.parse(cleanedContent);\n } catch {\n return null;\n }\n },\n // Strategy 2: Extract JSON from between first {} or []\n () => {\n const jsonMatch = cleanedContent.match(/[\\{\\[].*[\\}\\]]/s);\n if (jsonMatch) {\n try {\n return JSON.parse(jsonMatch[0]);\n } catch {\n return null;\n }\n }\n return null;\n },\n // Strategy 3: Remove leading/trailing text and try parsing\n () => {\n const jsonMatch = cleanedContent.replace(/^[^{[]*|[^}\\]]*$/g, '');\n try {\n return JSON.parse(jsonMatch);\n } catch {\n return null;\n }\n },\n // Strategy 4: Use fixJsonWithAI\n () => {\n return fixJsonWithAI(cleanedContent);\n },\n // Strategy 5: Use fixBrokenJson\n () => {\n return fixBrokenJson(cleanedContent);\n },\n ];\n\n // Try each parsing strategy\n for (const strategy of jsonParsingStrategies) {\n const result = await strategy();\n if (result !== null) {\n return result as T;\n }\n }\n\n // If all strategies fail, throw an error\n console.error(`Failed to parse JSON from content: ${cleanedContent}. Original JSON: ${content}`);\n throw new Error('Unable to parse JSON response');\n } else {\n return content as T;\n }\n}\n", "import OpenAI from 'openai';\nimport { ImageGenerationOptions, LLMModel, DiscoImageModel, OPENAI_MODELS } from './types';\nimport { calculateImageCost } from './llm-config';\nimport { ImageGenerateParams, ImagesResponse } from 'openai/resources/images';\n\n/**\n * Enhanced ImagesResponse that includes cost calculation\n */\nexport interface ImageResponseWithUsage extends ImagesResponse {\n usage?: ImagesResponse['usage'] & {\n provider: string;\n model: DiscoImageModel;\n cost: number;\n visionModel?: LLMModel;\n };\n}\n\nexport const DEFAULT_IMAGE_MODEL: DiscoImageModel = 'gpt-image-2';\n\nexport const resolveImageModel = (model?: DiscoImageModel): DiscoImageModel => model ?? DEFAULT_IMAGE_MODEL;\n\nconst MULTIMODAL_VISION_MODELS: ReadonlySet<LLMModel> = new Set(OPENAI_MODELS);\n\n/**\n * Makes a call to the OpenAI Images API to generate images based on a text prompt.\n *\n * This function provides access to OpenAI's image generation capabilities with support for:\n * - Different output formats (JPEG, PNG, WebP)\n * - Various image sizes and quality settings\n * - Multiple image generation in a single call\n * - Base64 encoded image data return\n *\n * @example\n * // Basic image generation\n * const response = await makeImagesCall('A beautiful sunset over mountains');\n *\n * @example\n * // Custom options\n * const response = await makeImagesCall('A birthday cake', {\n * size: '1024x1024',\n * outputFormat: 'png',\n * quality: 'high',\n * count: 2\n * });\n *\n * @param prompt - The text prompt describing the image to generate\n * @param options - Configuration options for image generation. Includes:\n * - size: Image dimensions (uses OpenAI's size options)\n * - outputFormat: Image format ('jpeg', 'png', 'webp') - defaults to 'webp'\n * - compression: Compression level (number) - defaults to 50\n * - quality: Quality setting (uses OpenAI's quality options) - defaults to 'high'\n * - count: Number of images to generate - defaults to 1\n * - background: Background setting for transparency support\n * - moderation: Content moderation level\n * - apiKey: OpenAI API key (optional, falls back to environment variable)\n * @returns Promise<ImageResponseWithUsage> - The image generation response with cost information\n * @throws Error if the API call fails or invalid parameters are provided\n */\nexport async function makeImagesCall(\n prompt: string,\n options: ImageGenerationOptions = {}\n): Promise<ImageResponseWithUsage> {\n const {\n model,\n size = 'auto',\n outputFormat = 'webp',\n compression = 50,\n quality = 'high',\n count = 1,\n background = 'auto',\n moderation = 'auto',\n apiKey,\n visionModel,\n } = options;\n const imageModel = resolveImageModel(model);\n const supportedVisionModel = visionModel && MULTIMODAL_VISION_MODELS.has(visionModel) ? visionModel : undefined;\n if (visionModel && !supportedVisionModel) {\n console.warn(\n `Vision model ${visionModel} is not recognized as a multimodal OpenAI model. Ignoring for image usage metadata.`\n );\n }\n\n // Get API key\n const effectiveApiKey = apiKey || process.env.OPENAI_API_KEY;\n if (!effectiveApiKey) {\n throw new Error('OpenAI API key is not provided and OPENAI_API_KEY environment variable is not set');\n }\n\n // Validate inputs\n if (!prompt || typeof prompt !== 'string') {\n throw new Error('Prompt must be a non-empty string');\n }\n\n if (count && (count < 1 || count > 10)) {\n throw new Error('Count must be between 1 and 10');\n }\n\n if (compression && (compression < 0 || compression > 100)) {\n throw new Error('Compression must be between 0 and 100');\n }\n\n const openai = new OpenAI({\n apiKey: effectiveApiKey,\n });\n\n // Build the request parameters using OpenAI's type\n const requestParams: ImageGenerateParams = {\n model: imageModel,\n prompt,\n n: count || 1,\n size: size || 'auto',\n quality: quality || 'auto',\n background: background || 'auto',\n moderation: moderation || 'auto',\n };\n\n // Add output format if specified\n if (outputFormat) {\n requestParams.output_format = outputFormat;\n }\n\n // Add compression if specified\n if (compression !== undefined) {\n requestParams.output_compression = compression;\n }\n\n try {\n // Make the API call\n const response = await openai.images.generate(requestParams);\n\n // Validate response\n if (!response.data || response.data.length === 0) {\n throw new Error('No images returned from OpenAI Images API');\n }\n\n // Calculate cost\n const cost = calculateImageCost(imageModel, count || 1, quality, size);\n\n // Return the response with enhanced usage information\n const enhancedResponse: ImageResponseWithUsage = {\n ...response,\n usage: {\n // OpenAI Images response may not include usage details per image; preserve if present\n ...(response.usage ?? {\n input_tokens: 0,\n input_tokens_details: { image_tokens: 0, text_tokens: 0 },\n output_tokens: 0,\n total_tokens: 0,\n }),\n provider: 'openai',\n model: imageModel,\n cost,\n ...(supportedVisionModel ? { visionModel: supportedVisionModel } : {}),\n },\n };\n\n return enhancedResponse;\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Unknown error';\n throw new Error(`OpenAI Images API call failed: ${message}`);\n }\n} \n", "import OpenAI from 'openai';\nimport {\n ChatCompletionContentPart,\n ChatCompletionMessageParam,\n ChatCompletionCreateParams,\n} from 'openai/resources/chat';\n\nimport { calculateCost } from './llm-config';\nimport { parseResponse, normalizeModelName } from './llm-utils';\nimport { LLMResponse, LLMOptions, OpenAIModel, OpenAIResponseFormat, DeepseekModel, LLMModel } from './types';\n\n/**\n * Default options for Deepseek API calls\n */\nconst DEFAULT_DEEPSEEK_OPTIONS = {\n defaultModel: 'deepseek-chat' as DeepseekModel,\n};\n\n/**\n * Checks if the given model is a supported Deepseek model\n * @param model The model to check\n * @returns True if the model is supported, false otherwise\n */\nconst isSupportedDeepseekModel = (model: string): model is DeepseekModel => {\n return ['deepseek-chat', 'deepseek-reasoner'].includes(model);\n};\n\n/**\n * Checks if the given Deepseek model supports JSON output format\n * @param model The model to check\n * @returns True if JSON output is supported, false otherwise\n */\nconst supportsJsonOutput = (model: string): boolean => {\n return model === 'deepseek-chat';\n};\n\n/**\n * Checks if the given Deepseek model supports tool calling\n * @param model The model to check\n * @returns True if tool calling is supported, false otherwise\n */\nconst supportsToolCalling = (model: string): boolean => {\n return model === 'deepseek-chat';\n};\n\n/**\n * Gets the appropriate response format option for Deepseek API\n * \n * @param responseFormat The desired response format\n * @param model The model being used\n * @returns Object representing the Deepseek response format option\n */\nfunction getDeepseekResponseFormatOption(responseFormat: OpenAIResponseFormat, model: string): { type: 'text' } | { type: 'json_object' } {\n // Check if the model supports JSON output\n if (responseFormat !== 'text' && !supportsJsonOutput(model)) {\n console.warn(`Model ${model} does not support JSON output. Using text format instead.`);\n return { type: 'text' };\n }\n\n if (responseFormat === 'text') {\n return { type: 'text' };\n }\n if (responseFormat === 'json' || (typeof responseFormat === 'object' && responseFormat.type === 'json_schema')) {\n return { type: 'json_object' };\n }\n return { type: 'text' };\n}\n\n/**\n * Creates a completion using the Deepseek API\n * \n * @param content The content to pass to the API\n * @param responseFormat The desired format of the response\n * @param options Additional options for the API call\n * @returns Promise resolving to the API response\n */\nasync function createDeepseekCompletion(\n content: string | ChatCompletionContentPart[],\n responseFormat: OpenAIResponseFormat,\n options: LLMOptions = {}\n) {\n // Extract the model or use default\n const modelOption = options.model || DEFAULT_DEEPSEEK_OPTIONS.defaultModel;\n const normalizedModel = normalizeModelName(modelOption);\n \n // Validate model\n if (!isSupportedDeepseekModel(normalizedModel)) {\n throw new Error(`Unsupported Deepseek model: ${normalizedModel}. Please use 'deepseek-chat' or 'deepseek-reasoner'.`);\n }\n\n // Check if tools are requested with a model that doesn't support them\n if (options.tools && options.tools.length > 0 && !supportsToolCalling(normalizedModel)) {\n throw new Error(`Model ${normalizedModel} does not support tool calling.`);\n }\n\n const apiKey = options.apiKey || process.env.DEEPSEEK_API_KEY;\n if (!apiKey) {\n throw new Error('Deepseek API key is not provided and DEEPSEEK_API_KEY environment variable is not set');\n }\n\n // Initialize OpenAI client with Deepseek API URL\n const openai = new OpenAI({\n apiKey,\n baseURL: 'https://api.deepseek.com',\n });\n\n const messages: ChatCompletionMessageParam[] = [];\n\n // Add system message with developer prompt if present\n if (options.developerPrompt) {\n messages.push({\n role: 'system',\n content: options.developerPrompt,\n });\n }\n\n // Add context if present\n if (options.context) {\n messages.push(...options.context);\n }\n\n // Add user content\n if (typeof content === 'string') {\n messages.push({\n role: 'user',\n content,\n });\n } else {\n messages.push({\n role: 'user',\n content,\n });\n }\n\n // If JSON response format, include a hint in the system prompt\n if ((responseFormat === 'json' || (typeof responseFormat === 'object' && responseFormat.type === 'json_schema')) \n && supportsJsonOutput(normalizedModel)) {\n // If there's no system message yet, add one\n if (!messages.some(m => m.role === 'system')) {\n messages.unshift({\n role: 'system',\n content: 'Please respond in valid JSON format.',\n });\n } else {\n // Append to existing system message\n const systemMsgIndex = messages.findIndex(m => m.role === 'system');\n const systemMsg = messages[systemMsgIndex];\n if (typeof systemMsg.content === 'string') {\n messages[systemMsgIndex] = {\n ...systemMsg,\n content: `${systemMsg.content} Please respond in valid JSON format.`,\n };\n }\n }\n }\n\n const queryOptions: ChatCompletionCreateParams = {\n model: normalizedModel,\n messages,\n response_format: getDeepseekResponseFormatOption(responseFormat, normalizedModel),\n temperature: options.temperature,\n top_p: options.top_p,\n frequency_penalty: options.frequency_penalty,\n presence_penalty: options.presence_penalty,\n max_tokens: options.max_completion_tokens,\n };\n\n // Only add tools if the model supports them\n if (options.tools && supportsToolCalling(normalizedModel)) {\n queryOptions.tools = options.tools;\n }\n\n try {\n const completion = await openai.chat.completions.create(queryOptions);\n\n return {\n id: completion.id,\n content: completion.choices[0]?.message?.content || '',\n tool_calls: completion.choices[0]?.message?.tool_calls,\n usage: completion.usage || {\n prompt_tokens: 0,\n completion_tokens: 0,\n total_tokens: 0,\n },\n system_fingerprint: completion.system_fingerprint,\n provider: 'deepseek',\n model: normalizedModel as DeepseekModel,\n };\n } catch (error) {\n console.error('Error calling Deepseek API:', error);\n throw error;\n }\n}\n\n/**\n * Makes a call to the Deepseek AI API.\n *\n * @param content The content to pass to the LLM. Can be a string or an array of content parts.\n * @param responseFormat The format of the response. Defaults to 'json'.\n * @param options Configuration options including model ('deepseek-chat' or 'deepseek-reasoner'), tools, and apiKey.\n * @return A promise that resolves to the response from the Deepseek API.\n */\nexport const makeDeepseekCall = async <T = string>(\n content: string | ChatCompletionContentPart[],\n responseFormat: OpenAIResponseFormat = 'json',\n options: LLMOptions = {}\n): Promise<LLMResponse<T>> => {\n // Set default model if not provided\n const mergedOptions = {\n ...options,\n };\n\n if (!mergedOptions.model) {\n mergedOptions.model = DEFAULT_DEEPSEEK_OPTIONS.defaultModel;\n }\n\n const modelName = normalizeModelName(mergedOptions.model as string);\n \n // Check if the requested response format is compatible with the model\n if (responseFormat !== 'text' && !supportsJsonOutput(modelName)) {\n console.warn(`Model ${modelName} does not support JSON output. Will return error in the response.`);\n return {\n response: {\n error: `Model ${modelName} does not support JSON output format.`\n } as unknown as T,\n usage: {\n prompt_tokens: 0,\n completion_tokens: 0,\n reasoning_tokens: 0,\n provider: 'deepseek',\n model: modelName as DeepseekModel,\n cache_hit_tokens: 0,\n cost: 0,\n },\n tool_calls: undefined,\n };\n }\n\n // Check if tools are requested with a model that doesn't support them\n if (mergedOptions.tools && mergedOptions.tools.length > 0 && !supportsToolCalling(modelName)) {\n console.warn(`Model ${modelName} does not support tool calling. Will return error in the response.`);\n return {\n response: {\n error: `Model ${modelName} does not support tool calling.`\n } as unknown as T,\n usage: {\n prompt_tokens: 0,\n completion_tokens: 0,\n reasoning_tokens: 0,\n provider: 'deepseek',\n model: modelName as DeepseekModel,\n cache_hit_tokens: 0,\n cost: 0,\n },\n tool_calls: undefined,\n };\n }\n\n try {\n const completion = await createDeepseekCompletion(content, responseFormat, mergedOptions);\n\n // Handle tool calls similarly to OpenAI\n if (completion.tool_calls && completion.tool_calls.length > 0) {\n const fnCalls = completion.tool_calls\n .filter((tc) => tc.type === 'function')\n .map((tc) => ({\n id: tc.id,\n name: (tc as Extract<typeof tc, { type: 'function' }>).function.name,\n arguments: JSON.parse((tc as Extract<typeof tc, { type: 'function' }>).function.arguments),\n }));\n return {\n response: { tool_calls: fnCalls } as T,\n usage: {\n prompt_tokens: completion.usage.prompt_tokens,\n completion_tokens: completion.usage.completion_tokens,\n reasoning_tokens: 0, // Deepseek doesn't provide reasoning tokens separately\n provider: 'deepseek',\n model: completion.model,\n cache_hit_tokens: 0, // Not provided directly in API response\n cost: calculateCost(\n 'deepseek',\n completion.model,\n completion.usage.prompt_tokens,\n completion.usage.completion_tokens,\n 0,\n 0 // Cache hit tokens (not provided in the response)\n ),\n },\n tool_calls: completion.tool_calls,\n };\n }\n\n // Handle regular responses\n const parsedResponse = await parseResponse<T>(completion.content, responseFormat);\n if (parsedResponse === null) {\n throw new Error('Failed to parse Deepseek response');\n }\n\n return {\n response: parsedResponse,\n usage: {\n prompt_tokens: completion.usage.prompt_tokens,\n completion_tokens: completion.usage.completion_tokens,\n reasoning_tokens: 0, // Deepseek doesn't provide reasoning tokens separately\n provider: 'deepseek',\n model: completion.model,\n cache_hit_tokens: 0, // Not provided directly in API response\n cost: calculateCost(\n 'deepseek',\n completion.model,\n completion.usage.prompt_tokens,\n completion.usage.completion_tokens,\n 0,\n 0 // Cache hit tokens (not provided in the response)\n ),\n },\n tool_calls: completion.tool_calls,\n };\n } catch (error) {\n // If there's an error due to incompatible features, return a structured error\n console.error('Error in Deepseek API call:', error);\n return {\n response: {\n error: error instanceof Error ? error.message : 'Unknown error'\n } as unknown as T,\n usage: {\n prompt_tokens: 0,\n completion_tokens: 0,\n reasoning_tokens: 0,\n provider: 'deepseek',\n model: modelName as DeepseekModel,\n cache_hit_tokens: 0,\n cost: 0,\n },\n tool_calls: undefined,\n };\n }\n};\n", "import { log as baseLog } from './logging';\nimport { LogOptions } from './types/logging-types';\nimport {\n Period,\n IntradayReporting,\n PeriodDates,\n MarketTimeParams,\n OutputFormat,\n MarketOpenCloseResult,\n MarketStatus,\n MarketTimesConfig,\n TradingDaysBackOptions,\n} from './types/market-time-types';\nimport { marketHolidays, marketEarlyCloses } from './market-hours';\n\n// Constants for NY market times (Eastern Time)\nexport const MARKET_CONFIG = {\n TIMEZONE: 'America/New_York',\n UTC_OFFSET_STANDARD: -5, // EST\n UTC_OFFSET_DST: -4, // EDT\n TIMES: {\n EXTENDED_START: { hour: 4, minute: 0 },\n MARKET_OPEN: { hour: 9, minute: 30 },\n EARLY_MARKET_END: { hour: 10, minute: 0 },\n MARKET_CLOSE: { hour: 16, minute: 0 },\n EARLY_CLOSE: { hour: 13, minute: 0 },\n EXTENDED_END: { hour: 20, minute: 0 },\n EARLY_EXTENDED_END: { hour: 17, minute: 0 },\n },\n} as const;\n\nconst log = (message: string, options: LogOptions = { type: 'info' }) => {\n baseLog(message, { ...options, source: 'MarketTime' });\n};\n\n// Helper: Get NY offset for a given UTC date (DST rules for US)\n/**\n * Returns the NY timezone offset (in hours) for a given UTC date, accounting for US DST rules.\n * @param date - UTC date\n * @returns offset in hours (-5 for EST, -4 for EDT)\n */\nfunction getNYOffset(date: Date): number {\n // US DST starts 2nd Sunday in March, ends 1st Sunday in November\n const year = date.getUTCFullYear();\n const dstStart = getNthWeekdayOfMonth(year, 3, 0, 2); // March, Sunday, 2nd\n const dstEnd = getNthWeekdayOfMonth(year, 11, 0, 1); // November, Sunday, 1st\n const utcTime = date.getTime();\n\n if (utcTime >= dstStart.getTime() && utcTime < dstEnd.getTime()) {\n return MARKET_CONFIG.UTC_OFFSET_DST;\n }\n return MARKET_CONFIG.UTC_OFFSET_STANDARD;\n}\n\n// Helper: Get nth weekday of month in UTC\n/**\n * Returns the nth weekday of a given month in UTC.\n * @param year - Year\n * @param month - 1-based month (e.g. March = 3)\n * @param weekday - 0=Sunday, 1=Monday, ...\n * @param n - nth occurrence\n * @returns Date object for the nth weekday\n */\nfunction getNthWeekdayOfMonth(year: number, month: number, weekday: number, n: number): Date {\n // month: 1-based (March = 3), weekday: 0=Sunday\n const firstDay = new Date(Date.UTC(year, month - 1, 1));\n let count = 0;\n for (let d = 1; d <= 31; d++) {\n const date = new Date(Date.UTC(year, month - 1, d));\n if (date.getUTCMonth() !== month - 1) break;\n if (date.getUTCDay() === weekday) {\n count++;\n if (count === n) return date;\n }\n }\n // fallback: last day of month\n return new Date(Date.UTC(year, month - 1, 28));\n}\n\n// Helper: Convert UTC date to NY time (returns new Date object)\n/**\n * Converts a UTC date to NY time (returns a new Date object).\n * @param date - UTC date\n * @returns Date object in NY time\n */\nfunction toNYTime(date: Date): Date {\n const offset = getNYOffset(date);\n // NY offset in hours\n const utcMillis = date.getTime();\n const nyMillis = utcMillis + offset * 60 * 60 * 1000;\n return new Date(nyMillis);\n}\n\n// Helper: Convert NY time to UTC (returns new Date object)\n/**\n * Converts a NY time date to UTC (returns a new Date object).\n * @param date - NY time date\n * @returns Date object in UTC\n */\nfunction fromNYTime(date: Date): Date {\n const offset = getNYOffset(date);\n const nyMillis = date.getTime();\n const utcMillis = nyMillis - offset * 60 * 60 * 1000;\n return new Date(utcMillis);\n}\n\n// Helper: Format date in ISO, unix, etc.\n/**\n * Formats a date in ISO, unix-seconds, or unix-ms format.\n * @param date - Date object\n * @param outputFormat - Output format ('iso', 'unix-seconds', 'unix-ms')\n * @returns Formatted date string or number\n */\nfunction formatDate(date: Date, outputFormat: OutputFormat = 'iso'): string | number {\n switch (outputFormat) {\n case 'unix-seconds':\n return Math.floor(date.getTime() / 1000);\n case 'unix-ms':\n return date.getTime();\n case 'iso':\n default:\n return date.toISOString();\n }\n}\n\n// Helper: Format date in NY locale string\n/**\n * Formats a date in NY locale string.\n * @param date - Date object\n * @returns NY locale string\n */\nfunction formatNYLocale(date: Date): string {\n return date.toLocaleString('en-US', { timeZone: 'America/New_York' });\n}\n\n// Market calendar logic\n/**\n * Market calendar logic for holidays, weekends, and market days.\n */\nclass MarketCalendar {\n /**\n * Checks if a date is a weekend in NY time.\n * @param date - Date object\n * @returns true if weekend, false otherwise\n */\n isWeekend(date: Date): boolean {\n const day = toNYTime(date).getUTCDay();\n return day === 0 || day === 6;\n }\n\n /**\n * Checks if a date is a market holiday in NY time.\n * @param date - Date object\n * @returns true if holiday, false otherwise\n */\n isHoliday(date: Date): boolean {\n const nyDate = toNYTime(date);\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth() + 1;\n const day = nyDate.getUTCDate();\n const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;\n const yearHolidays = marketHolidays[year];\n if (!yearHolidays) return false;\n return Object.values(yearHolidays).some((holiday) => holiday.date === formattedDate);\n }\n\n /**\n * Checks if a date is an early close day in NY time.\n * @param date - Date object\n * @returns true if early close, false otherwise\n */\n isEarlyCloseDay(date: Date): boolean {\n const nyDate = toNYTime(date);\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth() + 1;\n const day = nyDate.getUTCDate();\n const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;\n const yearEarlyCloses = marketEarlyCloses[year];\n return yearEarlyCloses && yearEarlyCloses[formattedDate] !== undefined;\n }\n\n /**\n * Gets the early close time (in minutes from midnight) for a given date.\n * @param date - Date object\n * @returns minutes from midnight or null\n */\n getEarlyCloseTime(date: Date): number | null {\n const nyDate = toNYTime(date);\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth() + 1;\n const day = nyDate.getUTCDate();\n const formattedDate = `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;\n const yearEarlyCloses = marketEarlyCloses[year];\n if (yearEarlyCloses && yearEarlyCloses[formattedDate]) {\n const [hours, minutes] = yearEarlyCloses[formattedDate].time.split(':').map(Number);\n return hours * 60 + minutes;\n }\n return null;\n }\n\n /**\n * Checks if a date is a market day (not weekend or holiday).\n * @param date - Date object\n * @returns true if market day, false otherwise\n */\n isMarketDay(date: Date): boolean {\n return !this.isWeekend(date) && !this.isHoliday(date);\n }\n\n /**\n * Gets the next market day after the given date.\n * @param date - Date object\n * @returns Date object for next market day\n */\n getNextMarketDay(date: Date): Date {\n let nextDay = new Date(date.getTime() + 24 * 60 * 60 * 1000);\n while (!this.isMarketDay(nextDay)) {\n nextDay = new Date(nextDay.getTime() + 24 * 60 * 60 * 1000);\n }\n return nextDay;\n }\n\n /**\n * Gets the previous market day before the given date.\n * @param date - Date object\n * @returns Date object for previous market day\n */\n getPreviousMarketDay(date: Date): Date {\n let prevDay = new Date(date.getTime() - 24 * 60 * 60 * 1000);\n while (!this.isMarketDay(prevDay)) {\n prevDay = new Date(prevDay.getTime() - 24 * 60 * 60 * 1000);\n }\n return prevDay;\n }\n}\n\n// Market open/close times\n/**\n * Returns market open/close times for a given date, including extended and early closes.\n * @param date - Date object\n * @returns MarketOpenCloseResult\n */\nfunction getMarketTimes(date: Date): MarketOpenCloseResult {\n const calendar = new MarketCalendar();\n const nyDate = toNYTime(date);\n if (!calendar.isMarketDay(date)) {\n return {\n marketOpen: false,\n open: null,\n close: null,\n openExt: null,\n closeExt: null,\n };\n }\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth();\n const day = nyDate.getUTCDate();\n\n // Helper to build NY time for a given hour/minute\n function buildNYTime(hour: number, minute: number): Date {\n const d = new Date(Date.UTC(year, month, day, hour, minute, 0, 0));\n return fromNYTime(d);\n }\n\n let open = buildNYTime(MARKET_CONFIG.TIMES.MARKET_OPEN.hour, MARKET_CONFIG.TIMES.MARKET_OPEN.minute);\n let close = buildNYTime(MARKET_CONFIG.TIMES.MARKET_CLOSE.hour, MARKET_CONFIG.TIMES.MARKET_CLOSE.minute);\n let openExt = buildNYTime(MARKET_CONFIG.TIMES.EXTENDED_START.hour, MARKET_CONFIG.TIMES.EXTENDED_START.minute);\n let closeExt = buildNYTime(MARKET_CONFIG.TIMES.EXTENDED_END.hour, MARKET_CONFIG.TIMES.EXTENDED_END.minute);\n\n if (calendar.isEarlyCloseDay(date)) {\n close = buildNYTime(MARKET_CONFIG.TIMES.EARLY_CLOSE.hour, MARKET_CONFIG.TIMES.EARLY_CLOSE.minute);\n closeExt = buildNYTime(MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.hour, MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.minute);\n }\n\n return {\n marketOpen: true,\n open,\n close,\n openExt,\n closeExt,\n };\n}\n\n// Is within market hours\n/**\n * Checks if a date/time is within market hours, extended hours, or continuous.\n * @param date - Date object\n * @param intradayReporting - 'market_hours', 'extended_hours', or 'continuous'\n * @returns true if within hours, false otherwise\n */\nexport function isWithinMarketHours(date: Date, intradayReporting: IntradayReporting = 'market_hours'): boolean {\n const calendar = new MarketCalendar();\n if (!calendar.isMarketDay(date)) return false;\n const nyDate = toNYTime(date);\n const minutes = nyDate.getUTCHours() * 60 + nyDate.getUTCMinutes();\n\n switch (intradayReporting) {\n case 'extended_hours': {\n let endMinutes = MARKET_CONFIG.TIMES.EXTENDED_END.hour * 60 + MARKET_CONFIG.TIMES.EXTENDED_END.minute;\n if (calendar.isEarlyCloseDay(date)) {\n endMinutes = MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.hour * 60 + MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.minute;\n }\n const startMinutes = MARKET_CONFIG.TIMES.EXTENDED_START.hour * 60 + MARKET_CONFIG.TIMES.EXTENDED_START.minute;\n return minutes >= startMinutes && minutes <= endMinutes;\n }\n case 'continuous':\n return true;\n default: {\n let endMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n if (calendar.isEarlyCloseDay(date)) {\n endMinutes = MARKET_CONFIG.TIMES.EARLY_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.EARLY_CLOSE.minute;\n }\n const startMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n return minutes >= startMinutes && minutes <= endMinutes;\n }\n }\n}\n\n// Get last full trading date\n/**\n * Returns the last full trading date (market close) for a given date.\n * @param currentDate - Date object (default: now)\n * @returns Date object for last full trading date\n */\nfunction getLastFullTradingDateImpl(currentDate: Date = new Date()): Date {\n const calendar = new MarketCalendar();\n const nyDate = toNYTime(currentDate);\n const minutes = nyDate.getUTCHours() * 60 + nyDate.getUTCMinutes();\n const marketOpenMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n let marketCloseMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n if (calendar.isEarlyCloseDay(currentDate)) {\n marketCloseMinutes = MARKET_CONFIG.TIMES.EARLY_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.EARLY_CLOSE.minute;\n }\n\n // If not a market day, or before open, or during market hours, return previous market day's close\n if (\n !calendar.isMarketDay(currentDate) ||\n minutes < marketOpenMinutes ||\n (minutes >= marketOpenMinutes && minutes < marketCloseMinutes)\n ) {\n const prevMarketDay = calendar.getPreviousMarketDay(currentDate);\n let prevCloseMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n if (calendar.isEarlyCloseDay(prevMarketDay)) {\n prevCloseMinutes = MARKET_CONFIG.TIMES.EARLY_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.EARLY_CLOSE.minute;\n }\n const prevNYDate = toNYTime(prevMarketDay);\n const year = prevNYDate.getUTCFullYear();\n const month = prevNYDate.getUTCMonth();\n const day = prevNYDate.getUTCDate();\n const closeHour = Math.floor(prevCloseMinutes / 60);\n const closeMinute = prevCloseMinutes % 60;\n return fromNYTime(new Date(Date.UTC(year, month, day, closeHour, closeMinute, 0, 0)));\n }\n\n // After market close or after extended hours, return today's close\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth();\n const day = nyDate.getUTCDate();\n const closeHour = Math.floor(marketCloseMinutes / 60);\n const closeMinute = marketCloseMinutes % 60;\n return fromNYTime(new Date(Date.UTC(year, month, day, closeHour, closeMinute, 0, 0)));\n}\n\n// Get day boundaries\n/**\n * Returns the start and end boundaries for a market day, extended hours, or continuous.\n * @param date - Date object\n * @param intradayReporting - 'market_hours', 'extended_hours', or 'continuous'\n * @returns Object with start and end Date\n */\nfunction getDayBoundaries(\n date: Date,\n intradayReporting: IntradayReporting = 'market_hours'\n): { start: Date; end: Date } {\n const calendar = new MarketCalendar();\n const nyDate = toNYTime(date);\n const year = nyDate.getUTCFullYear();\n const month = nyDate.getUTCMonth();\n const day = nyDate.getUTCDate();\n\n function buildNYTime(hour: number, minute: number, sec = 0, ms = 0): Date {\n const d = new Date(Date.UTC(year, month, day, hour, minute, sec, ms));\n return fromNYTime(d);\n }\n\n let start: Date;\n let end: Date;\n\n switch (intradayReporting) {\n case 'extended_hours':\n start = buildNYTime(MARKET_CONFIG.TIMES.EXTENDED_START.hour, MARKET_CONFIG.TIMES.EXTENDED_START.minute, 0, 0);\n end = buildNYTime(MARKET_CONFIG.TIMES.EXTENDED_END.hour, MARKET_CONFIG.TIMES.EXTENDED_END.minute, 59, 999);\n if (calendar.isEarlyCloseDay(date)) {\n end = buildNYTime(\n MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.hour,\n MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.minute,\n 59,\n 999\n );\n }\n break;\n case 'continuous':\n start = new Date(Date.UTC(year, month, day, 0, 0, 0, 0));\n end = new Date(Date.UTC(year, month, day, 23, 59, 59, 999));\n break;\n default:\n start = buildNYTime(MARKET_CONFIG.TIMES.MARKET_OPEN.hour, MARKET_CONFIG.TIMES.MARKET_OPEN.minute, 0, 0);\n end = buildNYTime(MARKET_CONFIG.TIMES.MARKET_CLOSE.hour, MARKET_CONFIG.TIMES.MARKET_CLOSE.minute, 59, 999);\n if (calendar.isEarlyCloseDay(date)) {\n end = buildNYTime(MARKET_CONFIG.TIMES.EARLY_CLOSE.hour, MARKET_CONFIG.TIMES.EARLY_CLOSE.minute, 59, 999);\n }\n break;\n }\n return { start, end };\n}\n\n// Period calculator\n/**\n * Calculates the start date for a given period ending at endDate.\n * @param endDate - Date object\n * @param period - Period string\n * @returns Date object for period start\n */\nfunction calculatePeriodStartDate(endDate: Date, period: Period): Date {\n const calendar = new MarketCalendar();\n let startDate: Date;\n switch (period) {\n case 'YTD':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear(), 0, 1));\n break;\n case '1D':\n startDate = calendar.getPreviousMarketDay(endDate);\n break;\n case '3D':\n startDate = new Date(endDate.getTime() - 3 * 24 * 60 * 60 * 1000);\n break;\n case '1W':\n startDate = new Date(endDate.getTime() - 7 * 24 * 60 * 60 * 1000);\n break;\n case '2W':\n startDate = new Date(endDate.getTime() - 14 * 24 * 60 * 60 * 1000);\n break;\n case '1M':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear(), endDate.getUTCMonth() - 1, endDate.getUTCDate()));\n break;\n case '3M':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear(), endDate.getUTCMonth() - 3, endDate.getUTCDate()));\n break;\n case '6M':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear(), endDate.getUTCMonth() - 6, endDate.getUTCDate()));\n break;\n case '1Y':\n startDate = new Date(Date.UTC(endDate.getUTCFullYear() - 1, endDate.getUTCMonth(), endDate.getUTCDate()));\n break;\n default:\n throw new Error(`Invalid period: ${period}`);\n }\n // Ensure start date is a market day\n while (!calendar.isMarketDay(startDate)) {\n startDate = calendar.getNextMarketDay(startDate);\n }\n return startDate;\n}\n\n// Get market time period\n/**\n * Returns the start and end dates for a market time period.\n * @param params - MarketTimeParams\n * @returns PeriodDates object\n */\nexport function getMarketTimePeriod(params: MarketTimeParams): PeriodDates {\n const { period, end = new Date(), intraday_reporting = 'market_hours', outputFormat = 'iso' } = params;\n\n if (!period) throw new Error('Period is required');\n const calendar = new MarketCalendar();\n\n const nyEndDate = toNYTime(end);\n let endDate: Date;\n const isCurrentMarketDay = calendar.isMarketDay(end);\n const isWithinHours = isWithinMarketHours(end, intraday_reporting);\n const minutes = nyEndDate.getUTCHours() * 60 + nyEndDate.getUTCMinutes();\n const marketStartMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n\n if (isCurrentMarketDay) {\n if (minutes < marketStartMinutes) {\n // Before market open - use previous day's close\n const lastMarketDay = calendar.getPreviousMarketDay(end);\n const { end: dayEnd } = getDayBoundaries(lastMarketDay, intraday_reporting);\n endDate = dayEnd;\n } else if (isWithinHours) {\n // During market hours - use current time\n endDate = end;\n } else {\n // After market close - use today's close\n const { end: dayEnd } = getDayBoundaries(end, intraday_reporting);\n endDate = dayEnd;\n }\n } else {\n // Not a market day - use previous market day's close\n const lastMarketDay = calendar.getPreviousMarketDay(end);\n const { end: dayEnd } = getDayBoundaries(lastMarketDay, intraday_reporting);\n endDate = dayEnd;\n }\n\n // Calculate start date\n const periodStartDate = calculatePeriodStartDate(endDate, period);\n const { start: dayStart } = getDayBoundaries(periodStartDate, intraday_reporting);\n\n if (endDate.getTime() < dayStart.getTime()) {\n throw new Error('Start date cannot be after end date');\n }\n\n return {\n start: formatDate(dayStart, outputFormat),\n end: formatDate(endDate, outputFormat),\n };\n}\n\n// Market status\n/**\n * Returns the current market status for a given date.\n * @param date - Date object (default: now)\n * @returns MarketStatus object\n */\nfunction getMarketStatusImpl(date: Date = new Date()): MarketStatus {\n const calendar = new MarketCalendar();\n const nyDate = toNYTime(date);\n const minutes = nyDate.getUTCHours() * 60 + nyDate.getUTCMinutes();\n const isMarketDay = calendar.isMarketDay(date);\n const isEarlyCloseDay = calendar.isEarlyCloseDay(date);\n\n const extendedStartMinutes = MARKET_CONFIG.TIMES.EXTENDED_START.hour * 60 + MARKET_CONFIG.TIMES.EXTENDED_START.minute;\n const marketStartMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n const earlyMarketEndMinutes =\n MARKET_CONFIG.TIMES.EARLY_MARKET_END.hour * 60 + MARKET_CONFIG.TIMES.EARLY_MARKET_END.minute;\n\n let marketCloseMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n let extendedEndMinutes = MARKET_CONFIG.TIMES.EXTENDED_END.hour * 60 + MARKET_CONFIG.TIMES.EXTENDED_END.minute;\n if (isEarlyCloseDay) {\n marketCloseMinutes = MARKET_CONFIG.TIMES.EARLY_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.EARLY_CLOSE.minute;\n extendedEndMinutes =\n MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.hour * 60 + MARKET_CONFIG.TIMES.EARLY_EXTENDED_END.minute;\n }\n\n let status: MarketStatus['status'];\n let nextStatus: MarketStatus['nextStatus'];\n let nextStatusTime: Date;\n let marketPeriod: MarketStatus['marketPeriod'];\n\n if (!isMarketDay) {\n status = 'closed';\n nextStatus = 'extended hours';\n marketPeriod = 'closed';\n const nextMarketDay = calendar.getNextMarketDay(date);\n nextStatusTime = getDayBoundaries(nextMarketDay, 'extended_hours').start;\n } else if (minutes < extendedStartMinutes) {\n status = 'closed';\n nextStatus = 'extended hours';\n marketPeriod = 'closed';\n nextStatusTime = getDayBoundaries(date, 'extended_hours').start;\n } else if (minutes < marketStartMinutes) {\n status = 'extended hours';\n nextStatus = 'open';\n marketPeriod = 'preMarket';\n nextStatusTime = getDayBoundaries(date, 'market_hours').start;\n } else if (minutes < marketCloseMinutes) {\n status = 'open';\n nextStatus = 'extended hours';\n marketPeriod = minutes < earlyMarketEndMinutes ? 'earlyMarket' : 'regularMarket';\n nextStatusTime = getDayBoundaries(date, 'market_hours').end;\n } else if (minutes < extendedEndMinutes) {\n status = 'extended hours';\n nextStatus = 'closed';\n marketPeriod = 'afterMarket';\n nextStatusTime = getDayBoundaries(date, 'extended_hours').end;\n } else {\n status = 'closed';\n nextStatus = 'extended hours';\n marketPeriod = 'closed';\n const nextMarketDay = calendar.getNextMarketDay(date);\n nextStatusTime = getDayBoundaries(nextMarketDay, 'extended_hours').start;\n }\n\n // I think using nyDate here may be wrong - should use current time? i.e. date.getTime()\n const nextStatusTimeDifference = nextStatusTime.getTime() - date.getTime();\n\n return {\n time: date,\n timeString: formatNYLocale(nyDate),\n status,\n nextStatus,\n marketPeriod,\n nextStatusTime,\n nextStatusTimeDifference,\n nextStatusTimeString: formatNYLocale(nextStatusTime),\n };\n}\n\n// API exports\n/**\n * Returns market open/close times for a given date.\n * @param options - { date?: Date }\n * @returns MarketOpenCloseResult\n */\nexport function getMarketOpenClose(options: { date?: Date } = {}): MarketOpenCloseResult {\n const { date = new Date() } = options;\n return getMarketTimes(date);\n}\n\n/**\n * Returns the start and end dates for a market time period as Date objects.\n * @param params - MarketTimeParams\n * @returns Object with start and end Date\n */\nexport function getStartAndEndDates(params: MarketTimeParams = {}): { start: Date; end: Date } {\n const { start, end } = getMarketTimePeriod(params);\n return {\n start: typeof start === 'string' || typeof start === 'number' ? new Date(start) : start,\n end: typeof end === 'string' || typeof end === 'number' ? new Date(end) : end,\n };\n}\n\n/**\n * Returns the last full trading date as a Date object.\n */\n/**\n * Returns the last full trading date as a Date object.\n * @param currentDate - Date object (default: now)\n * @returns Date object for last full trading date\n */\nexport function getLastFullTradingDate(currentDate: Date = new Date()): Date {\n return getLastFullTradingDateImpl(currentDate);\n}\n\n/**\n * Returns the last full trading date and formatted YYYYMMDD string.\n */\n/**\n * Returns the last full trading date and formatted YYYY-MM-DD string.\n * @param currentDate - Date object (default: now)\n * @returns Object with date and YYYYMMDD string\n */\nexport function getLastFullTradingDateInfo(currentDate: Date = new Date()): { date: Date; YYYYMMDD: string } {\n const date = getLastFullTradingDateImpl(currentDate);\n return {\n date,\n YYYYMMDD: `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, '0')}-${String(\n date.getUTCDate()\n ).padStart(2, '0')}`,\n };\n}\n\n/**\n * Returns the next market day after the reference date.\n * @param referenceDate - Date object (default: now)\n * @returns Object with date, yyyymmdd string, and ISO string\n */\nexport function getNextMarketDay({ referenceDate }: { referenceDate?: Date } = {}): {\n date: Date;\n yyyymmdd: string;\n dateISOString: string;\n} {\n const calendar = new MarketCalendar();\n const startDate = referenceDate ?? new Date();\n\n // Find the next trading day (UTC Date object)\n const nextDate = calendar.getNextMarketDay(startDate);\n\n // Convert to NY time before extracting Y-M-D parts\n const nyNext = toNYTime(nextDate);\n const yyyymmdd = `${nyNext.getUTCFullYear()}-${String(nyNext.getUTCMonth() + 1).padStart(2, '0')}-${String(\n nyNext.getUTCDate()\n ).padStart(2, '0')}`;\n\n return {\n date: nextDate, // raw Date, unchanged\n yyyymmdd, // correct trading date string\n dateISOString: nextDate.toISOString(),\n };\n}\n\n/**\n * Returns the previous market day before the reference date.\n * @param referenceDate - Date object (default: now)\n * @returns Object with date, yyyymmdd string, and ISO string\n */\nexport function getPreviousMarketDay({ referenceDate }: { referenceDate?: Date } = {}) {\n const calendar = new MarketCalendar();\n const startDate = referenceDate || new Date();\n const prevDate = calendar.getPreviousMarketDay(startDate);\n\n // convert to NY time first\n const nyPrev = toNYTime(prevDate); // \u2190 already in this file\n const yyyymmdd = `${nyPrev.getUTCFullYear()}-${String(nyPrev.getUTCMonth() + 1).padStart(2, '0')}-${String(\n nyPrev.getUTCDate()\n ).padStart(2, '0')}`;\n\n return {\n date: prevDate,\n yyyymmdd,\n dateISOString: prevDate.toISOString(),\n };\n}\n\n/**\n * Returns the trading date for a given time. Note: Just trims the date string; does not validate if the date is a market day.\n * @param time - a string, number (unix timestamp), or Date object representing the time\n * @returns the trading date as a string in YYYY-MM-DD format\n */\n/**\n * Returns the trading date for a given time in YYYY-MM-DD format (NY time).\n * @param time - string, number, or Date\n * @returns trading date string\n */\nexport function getTradingDate(time: string | number | Date): string {\n const date = typeof time === 'number' ? new Date(time) : typeof time === 'string' ? new Date(time) : time;\n const nyDate = toNYTime(date);\n return `${nyDate.getUTCFullYear()}-${String(nyDate.getUTCMonth() + 1).padStart(2, '0')}-${String(\n nyDate.getUTCDate()\n ).padStart(2, '0')}`;\n}\n\n/**\n * Returns the NY timezone offset string for a given date.\n * @param date - Date object (default: now)\n * @returns '-04:00' for EDT, '-05:00' for EST\n */\nexport function getNYTimeZone(date?: Date): '-04:00' | '-05:00' {\n const offset = getNYOffset(date || new Date());\n return offset === -4 ? '-04:00' : '-05:00';\n}\n\n/**\n * Returns the regular market open and close Date objects for a given trading day string in the\n * America/New_York timezone (NYSE/NASDAQ calendar).\n *\n * This helper is convenient when you have a calendar date like '2025-10-03' and want the precise\n * open and close Date values for that day. It internally:\n * - Determines the NY offset for the day using `getNYTimeZone()`.\n * - Anchors a noon-time Date on that day in NY time to avoid DST edge cases.\n * - Verifies the day is a market day via `isMarketDay()`.\n * - Fetches the open/close times via `getMarketOpenClose()`.\n *\n * Throws if the provided day is not a market day or if open/close times are unavailable.\n *\n * See also:\n * - `getNYTimeZone(date?: Date)`\n * - `isMarketDay(date: Date)`\n * - `getMarketOpenClose(options?: { date?: Date })`\n *\n * @param dateStr - Trading day string in 'YYYY-MM-DD' format (Eastern Time date)\n * @returns An object containing `{ open: Date; close: Date }`\n * @example\n * ```ts\n * const { open, close } = disco.time.getOpenCloseForTradingDay('2025-10-03');\n * ```\n */\nexport function getOpenCloseForTradingDay(dateStr: string): { open: Date; close: Date } {\n // Build a UTC midnight anchor for the date, then derive the NY offset for that day.\n const utcAnchor = new Date(`${dateStr}T00:00:00Z`);\n const nyOffset = getNYTimeZone(utcAnchor); // '-04:00' | '-05:00'\n\n // Create a NY-local noon date to avoid DST midnight transitions.\n const nyNoon = new Date(`${dateStr}T12:00:00${nyOffset}`);\n\n if (!isMarketDay(nyNoon)) {\n throw new Error(`Not a market day in ET: ${dateStr}`);\n }\n\n const { open, close } = getMarketOpenClose({ date: nyNoon });\n if (!open || !close) {\n throw new Error(`No market times available for ${dateStr}`);\n }\n\n return { open, close };\n}\n\n/**\n * Converts any date to the market time zone (America/New_York, Eastern Time).\n * Returns a new Date object representing the same moment in time but adjusted to NY/Eastern timezone.\n * Automatically handles daylight saving time transitions (EST/EDT).\n * \n * @param date - Date object to convert to market time zone\n * @returns Date object in NY/Eastern time zone\n * @example\n * ```typescript\n * const utcDate = new Date('2024-01-15T15:30:00Z'); // 3:30 PM UTC\n * const nyDate = convertDateToMarketTimeZone(utcDate); // 10:30 AM EST (winter) or 11:30 AM EDT (summer)\n * ```\n */\nexport function convertDateToMarketTimeZone(date: Date): Date {\n return toNYTime(date);\n}\n\n/**\n * Returns the current market status for a given date.\n * @param options - { date?: Date }\n * @returns MarketStatus object\n */\nexport function getMarketStatus(options: { date?: Date } = {}): MarketStatus {\n const { date = new Date() } = options;\n return getMarketStatusImpl(date);\n}\n\n/**\n * Checks if a date is a market day.\n * @param date - Date object\n * @returns true if market day, false otherwise\n */\nexport function isMarketDay(date: Date): boolean {\n const calendar = new MarketCalendar();\n return calendar.isMarketDay(date);\n}\n\n/**\n * Returns full trading days from market open to market close.\n * endDate is always the most recent market close (previous day's close if before open, today's close if after open).\n * days: 1 or not specified = that day's open; 2 = previous market day's open, etc.\n */\n/**\n * Returns full trading days from market open to market close.\n * @param options - { endDate?: Date, days?: number }\n * @returns Object with startDate and endDate\n */\nexport function getTradingStartAndEndDates(\n options: {\n endDate?: Date;\n days?: number;\n } = {}\n): { startDate: Date; endDate: Date } {\n const { endDate = new Date(), days = 1 } = options;\n const calendar = new MarketCalendar();\n\n // Find the most recent market close\n let endMarketDay = endDate;\n const nyEnd = toNYTime(endDate);\n const marketOpenMinutes = MARKET_CONFIG.TIMES.MARKET_OPEN.hour * 60 + MARKET_CONFIG.TIMES.MARKET_OPEN.minute;\n const marketCloseMinutes = MARKET_CONFIG.TIMES.MARKET_CLOSE.hour * 60 + MARKET_CONFIG.TIMES.MARKET_CLOSE.minute;\n const minutes = nyEnd.getUTCHours() * 60 + nyEnd.getUTCMinutes();\n\n if (\n !calendar.isMarketDay(endDate) ||\n minutes < marketOpenMinutes ||\n (minutes >= marketOpenMinutes && minutes < marketCloseMinutes)\n ) {\n // Before market open, not a market day, or during market hours: use previous market day\n endMarketDay = calendar.getPreviousMarketDay(endDate);\n } else {\n // After market close: use today\n endMarketDay = endDate;\n }\n\n // Get market close for endMarketDay\n const endClose = getMarketOpenClose({ date: endMarketDay }).close!;\n\n // Find start market day by iterating back over market days\n let startMarketDay = endMarketDay;\n let count = Math.max(1, days);\n for (let i = 1; i < count; i++) {\n startMarketDay = calendar.getPreviousMarketDay(startMarketDay);\n }\n // If days > 1, we need to go back (days-1) market days from endMarketDay\n if (days > 1) {\n startMarketDay = endMarketDay;\n for (let i = 1; i < days; i++) {\n startMarketDay = calendar.getPreviousMarketDay(startMarketDay);\n }\n }\n const startOpen = getMarketOpenClose({ date: startMarketDay }).open!;\n\n return { startDate: startOpen, endDate: endClose };\n}\n\n/**\n * Counts trading time between two dates (passed as standard Date objects), excluding weekends and holidays, and closed market hours, using other functions in this library.\n *\n * This function calculates the actual trading time between two dates by:\n * 1. Iterating through each calendar day between startDate and endDate (inclusive)\n * 2. For each day that is a market day (not weekend/holiday), getting market open/close times\n * 3. Calculating the overlap between the time range and market hours for that day\n * 4. Summing up all the trading minutes across all days\n *\n * The function automatically handles:\n * - Weekends (Saturday/Sunday) - skipped entirely\n * - Market holidays - skipped entirely\n * - Early close days (e.g. day before holidays) - uses early close time\n * - Times outside market hours - only counts time within 9:30am-4pm ET (or early close)\n *\n * Examples:\n * - 12pm to 3:30pm same day = 3.5 hours = 210 minutes = 0.54 days\n * - 9:30am to 4pm same day = 6.5 hours = 390 minutes = 1 day\n * - Friday 2pm to Monday 2pm = 6.5 hours (Friday 2pm-4pm + Monday 9:30am-2pm)\n *\n * @param startDate - Start date/time\n * @param endDate - End date/time (default: now)\n * @returns Object containing:\n * - days: Trading time as fraction of full trading days (6.5 hours = 1 day)\n * - hours: Trading time in hours\n * - minutes: Trading time in minutes\n */\nexport function countTradingDays(\n startDate: Date,\n endDate: Date = new Date()\n): {\n days: number;\n hours: number;\n minutes: number;\n} {\n const calendar = new MarketCalendar();\n\n // Ensure start is before end\n if (startDate.getTime() > endDate.getTime()) {\n throw new Error('Start date must be before end date');\n }\n\n let totalMinutes = 0;\n\n // Get the NY dates for iteration\n const startNY = toNYTime(startDate);\n const endNY = toNYTime(endDate);\n\n // Create date at start of first day (in NY time)\n const currentNY = new Date(\n Date.UTC(startNY.getUTCFullYear(), startNY.getUTCMonth(), startNY.getUTCDate(), 0, 0, 0, 0)\n );\n\n // Iterate through each calendar day\n while (currentNY.getTime() <= endNY.getTime()) {\n const currentUTC = fromNYTime(currentNY);\n\n // Check if this is a market day\n if (calendar.isMarketDay(currentUTC)) {\n // Get market hours for this day\n const marketTimes = getMarketTimes(currentUTC);\n\n if (marketTimes.marketOpen && marketTimes.open && marketTimes.close) {\n // Calculate the overlap between our time range and market hours\n const dayStart = Math.max(startDate.getTime(), marketTimes.open.getTime());\n const dayEnd = Math.min(endDate.getTime(), marketTimes.close.getTime());\n\n // Only count if there's actual overlap\n if (dayStart < dayEnd) {\n totalMinutes += (dayEnd - dayStart) / (1000 * 60);\n }\n }\n }\n\n // Move to next day\n currentNY.setUTCDate(currentNY.getUTCDate() + 1);\n }\n\n // Convert to days, hours, minutes\n const MINUTES_PER_TRADING_DAY = 390; // 6.5 hours\n const days = totalMinutes / MINUTES_PER_TRADING_DAY;\n const hours = totalMinutes / 60;\n const minutes = totalMinutes;\n\n return {\n days: Math.round(days * 1000) / 1000, // Round to 3 decimal places\n hours: Math.round(hours * 100) / 100, // Round to 2 decimal places\n minutes: Math.round(minutes),\n };\n}\n\n/**\n * Returns the trading day N days back from a reference date, along with its market open time.\n * Trading days are counted as full or half trading days (days that end count as 1 full trading day).\n * By default, the most recent completed trading day counts as day 1.\n * Set includeMostRecentFullDay to false to count strictly before that day.\n * \n * @param options - Object with:\n * - referenceDate: Date to count back from (default: now)\n * - days: Number of trading days to go back (must be an integer >= 1)\n * - includeMostRecentFullDay: Whether to include the most recent completed trading day (default: true)\n * @returns Object containing:\n * - date: Trading date in YYYY-MM-DD format\n * - marketOpenISO: Market open time as ISO string (e.g., \"2025-11-15T13:30:00.000Z\")\n * - unixTimestamp: Market open time as Unix timestamp in seconds\n * @example\n * ```typescript\n * // Get the trading day 1 day back (most recent full trading day)\n * const result = getTradingDaysBack({ days: 1 });\n * console.log(result.date); // \"2025-11-01\"\n * console.log(result.marketOpenISO); // \"2025-11-01T13:30:00.000Z\"\n * console.log(result.unixTimestamp); // 1730466600\n * \n * // Get the trading day 5 days back from a specific date\n * const result2 = getTradingDaysBack({ \n * referenceDate: new Date('2025-11-15T12:00:00-05:00'), \n * days: 5 \n * });\n * ```\n */\nexport function getTradingDaysBack(options: TradingDaysBackOptions): {\n date: string;\n marketOpenISO: string;\n unixTimestamp: number;\n} {\n const calendar = new MarketCalendar();\n const { referenceDate, days, includeMostRecentFullDay = true } = options;\n const refDate = referenceDate || new Date();\n const daysBack = days;\n\n if (!Number.isInteger(daysBack) || daysBack < 1) {\n throw new Error('days must be an integer >= 1');\n }\n\n // Start from the last full trading date relative to reference\n let targetDate = getLastFullTradingDateImpl(refDate);\n\n if (!includeMostRecentFullDay) {\n targetDate = calendar.getPreviousMarketDay(targetDate);\n }\n\n // Go back the specified number of days (we're already at day 1, so go back days-1 more)\n for (let i = 1; i < daysBack; i++) {\n targetDate = calendar.getPreviousMarketDay(targetDate);\n }\n\n // Get market open time for this date\n const marketTimes = getMarketTimes(targetDate);\n if (!marketTimes.open) {\n throw new Error(`No market open time for target date`);\n }\n\n // Format the date string (YYYY-MM-DD) in NY time\n const nyDate = toNYTime(marketTimes.open);\n const dateStr = `${nyDate.getUTCFullYear()}-${String(nyDate.getUTCMonth() + 1).padStart(2, '0')}-${String(nyDate.getUTCDate()).padStart(2, '0')}`;\n\n const marketOpenISO = marketTimes.open.toISOString();\n const unixTimestamp = Math.floor(marketTimes.open.getTime() / 1000);\n\n return {\n date: dateStr,\n marketOpenISO,\n unixTimestamp,\n };\n}\n\n// Export MARKET_TIMES for compatibility\nexport const MARKET_TIMES: MarketTimesConfig = {\n TIMEZONE: MARKET_CONFIG.TIMEZONE,\n PRE: {\n START: { HOUR: 4, MINUTE: 0, MINUTES: 240 },\n END: { HOUR: 9, MINUTE: 30, MINUTES: 570 },\n },\n EARLY_MORNING: {\n START: { HOUR: 9, MINUTE: 30, MINUTES: 570 },\n END: { HOUR: 10, MINUTE: 0, MINUTES: 600 },\n },\n EARLY_CLOSE_BEFORE_HOLIDAY: {\n START: { HOUR: 9, MINUTE: 30, MINUTES: 570 },\n END: { HOUR: 13, MINUTE: 0, MINUTES: 780 },\n },\n EARLY_EXTENDED_BEFORE_HOLIDAY: {\n START: { HOUR: 13, MINUTE: 0, MINUTES: 780 },\n END: { HOUR: 17, MINUTE: 0, MINUTES: 1020 },\n },\n REGULAR: {\n START: { HOUR: 9, MINUTE: 30, MINUTES: 570 },\n END: { HOUR: 16, MINUTE: 0, MINUTES: 960 },\n },\n EXTENDED: {\n START: { HOUR: 4, MINUTE: 0, MINUTES: 240 },\n END: { HOUR: 20, MINUTE: 0, MINUTES: 1200 },\n },\n};\n", "// market-hours.ts\n\nexport interface HolidayDetails {\n date: string;\n}\n\nexport interface MarketHolidaysForYear {\n [holidayName: string]: HolidayDetails;\n}\n\nexport interface MarketHolidays {\n [year: number]: MarketHolidaysForYear;\n}\n\nexport interface EarlyCloseDetails {\n date: string;\n time: string;\n optionsTime: string;\n notes: string;\n}\n\nexport interface EarlyClosesForYear {\n [date: string]: EarlyCloseDetails;\n}\n\nexport interface MarketEarlyCloses {\n [year: number]: EarlyClosesForYear;\n}\n\nexport const marketHolidays: MarketHolidays = {\n 2024: {\n \"New Year's Day\": { date: '2024-01-01' },\n 'Martin Luther King, Jr. Day': { date: '2024-01-15' },\n \"Washington's Birthday\": { date: '2024-02-19' },\n 'Good Friday': { date: '2024-03-29' },\n 'Memorial Day': { date: '2024-05-27' },\n 'Juneteenth National Independence Day': { date: '2024-06-19' },\n 'Independence Day': { date: '2024-07-04' },\n 'Labor Day': { date: '2024-09-02' },\n 'Thanksgiving Day': { date: '2024-11-28' },\n 'Christmas Day': { date: '2024-12-25' },\n },\n 2025: {\n \"New Year's Day\": { date: '2025-01-01' },\n 'Jimmy Carter Memorial Day': { date: '2025-01-09' },\n 'Martin Luther King, Jr. Day': { date: '2025-01-20' },\n \"Washington's Birthday\": { date: '2025-02-17' },\n 'Good Friday': { date: '2025-04-18' },\n 'Memorial Day': { date: '2025-05-26' },\n 'Juneteenth National Independence Day': { date: '2025-06-19' },\n 'Independence Day': { date: '2025-07-04' },\n 'Labor Day': { date: '2025-09-01' },\n 'Thanksgiving Day': { date: '2025-11-27' },\n 'Christmas Day': { date: '2025-12-25' },\n },\n 2026: {\n \"New Year's Day\": { date: '2026-01-01' },\n 'Martin Luther King, Jr. Day': { date: '2026-01-19' },\n \"Washington's Birthday\": { date: '2026-02-16' },\n 'Good Friday': { date: '2026-04-03' },\n 'Memorial Day': { date: '2026-05-25' },\n 'Juneteenth National Independence Day': { date: '2026-06-19' },\n 'Independence Day': { date: '2026-07-03' },\n 'Labor Day': { date: '2026-09-07' },\n 'Thanksgiving Day': { date: '2026-11-26' },\n 'Christmas Day': { date: '2026-12-25' },\n },\n};\n\nexport const marketEarlyCloses: MarketEarlyCloses = {\n 2024: {\n '2024-07-03': {\n date: '2024-07-03',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Wednesday, July 3, 2024 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2024-11-29': {\n date: '2024-11-29',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Friday, November 29, 2024 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2024-12-24': {\n date: '2024-12-24',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Tuesday, December 24, 2024 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n },\n 2025: {\n '2025-07-03': {\n date: '2025-07-03',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Thursday, July 3, 2025 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2025-11-28': {\n date: '2025-11-28',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Friday, November 28, 2025 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2025-12-24': {\n date: '2025-12-24',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Wednesday, December 24, 2025 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n },\n 2026: {\n '2026-07-02': {\n date: '2026-07-02',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Independence Day observed, market closes early at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2026-11-27': {\n date: '2026-11-27',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Friday, November 27, 2026 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n '2026-12-24': {\n date: '2026-12-24',\n time: '13:00',\n optionsTime: '13:15',\n notes:\n 'Market closes early on Thursday, December 24, 2026 at 1:00 p.m. (1:15 p.m. for eligible options). NYSE American Equities, NYSE Arca Equities, NYSE Chicago, and NYSE National late trading sessions will close at 5:00 p.m. Eastern Time.',\n },\n },\n};\n"],
5
5
  "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,IAAM,gBAAgB;AAAA,EAC3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAOO,SAAS,cAAc,OAAqC;AACjE,SA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AA,EAC5C;AACF;;;AT1hCO,IAAM,QAAQ;AAAA,EACnB,OAAO;AAAA,EACP,KAAK;AAAA,IACH,MAAU;AAAA,IACV;AAAA,IACA,MAAe;AAAA,IACf,QAAkB;AAAA,EACpB;AAAA,EACA;AACF;",
6
6
  "names": ["import_openai", "OpenAI", "OpenAI", "openai", "import_openai", "openai", "OpenAI", "import_openai", "openai", "OpenAI", "year", "month", "day", "closeHour", "closeMinute", "isMarketDay"]
7
7
  }