commit 1f0901d04d84180154b831dd815e8571b45f8a2c Author: Raj Sharma Date: Sun Oct 6 13:56:33 2024 +0530 Initial commit with the current state diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..56e5e28 --- /dev/null +++ b/.gitignore @@ -0,0 +1,183 @@ +# Based on https://raw.githubusercontent.com/github/gitignore/main/Node.gitignore + +# Logs + +logs +_.log +npm-debug.log_ +yarn-debug.log* +yarn-error.log* +lerna-debug.log* +.pnpm-debug.log* + +# Diagnostic reports (https://nodejs.org/api/report.html) + +report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json + +# Runtime data + +pids +_.pid +_.seed +\*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover + +lib-cov + +# Coverage directory used by tools like istanbul + +coverage +\*.lcov + +# nyc test coverage + +.nyc_output + +# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) + +.grunt + +# Bower dependency directory (https://bower.io/) + +bower_components + +# node-waf configuration + +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) + +build/Release + +# Dependency directories + +node_modules/ +jspm_packages/ + +# Snowpack dependency directory (https://snowpack.dev/) + +web_modules/ + +# TypeScript cache + +\*.tsbuildinfo + +# Optional npm cache directory + +.npm + +# Optional eslint cache + +.eslintcache + +# Optional stylelint cache + +.stylelintcache + +# Microbundle cache + +.rpt2_cache/ +.rts2_cache_cjs/ +.rts2_cache_es/ +.rts2_cache_umd/ + +# Optional REPL history + +.node_repl_history + +# Output of 'npm pack' + +\*.tgz + +# Yarn Integrity file + +.yarn-integrity + +# dotenv environment variable files + +.env +.env.development.local +.env.test.local +.env.production.local +.env.local + +# parcel-bundler cache (https://parceljs.org/) + +.cache +.parcel-cache + +# Next.js build output + +.next +out + +# Nuxt.js build / generate output + +.nuxt +dist + +# Gatsby files + +.cache/ + +# Comment in the public line in if your project uses Gatsby and not Next.js + +# https://nextjs.org/blog/next-9-1#public-directory-support + +# public + +# vuepress build output + +.vuepress/dist + +# vuepress v2.x temp and cache directory + +.temp +.cache + +# Docusaurus cache and generated files + +.docusaurus + +# Serverless directories + +.serverless/ + +# FuseBox cache + +.fusebox/ + +# DynamoDB Local files + +.dynamodb/ + +# TernJS port file + +.tern-port + +# Stores VSCode versions used for testing VSCode extensions + +.vscode-test + +# yarn v2 + +.yarn/cache +.yarn/unplugged +.yarn/build-state.yml +.yarn/install-state.gz +.pnp.\* + +# IntelliJ based IDEs +.idea + +# Finder (MacOS) folder config +.DS_Store + + +data +vosk-* +.wwebjs* +apiUsage* +*.db +*.db-* \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..efb16fc --- /dev/null +++ b/README.md @@ -0,0 +1,65 @@ +# anya + +cheaper jarvis + +Current Abilities: + +- Multi user support. +- Support for discord for user interaction and whatsapp for events. +- Support for voice input through on_voice_message event. +- Support for external events to trigger anya to execute any given instruction. +- Support a schedule to trigger anya to execute any given instruction. +- Can store memories for certain tasks. + +Current Tools & Managers: + +- Calculator: Can perform basic arithmetic operations. +- Get time: Can tell the current time. +- Calendar Manager (Uses CALDAV): + - Can manage a user's calendar. (not yet configurable per user). +- Cat Images: Can fetch random cat images. +- Chat search: Can search for a chat message in a convo. +- Communications Manager + - Send Email: Can send an email to a user. + - Send Message: Can send a message to a user. (supported platforms: discord, whatsapp) +- Docker Container Shell: Can execute shell commands in an isolated docker container. +- Events Manager + - CRUD on Events: Setup events that can be listened to. (webhook based, need a one time manual setup for each event). + - CRUD on Event Listeners: Setup event listeners that can call anya with a given instruction. once that event is triggered. +- Files Tools (Currently disabled by default) + - CRUD on a single s3/minio bucket. +- Goole Search (Currently disabled): Can search google for a given query. +- Home Assistant Manager: + - Can update Services: Can run services to control devices on a home assistant instance. +- LinkWarden Manager: + - CRUD on Links: Manage links on a linkwarden instance. +- Meme Generator: Can generate memes. +- Memory Manager: + - CRUD on Memories: Manage memories for anya and other managers. +- Notes Manager: + - CRUD on Notes: Manage notes with a defined template using webdav to perform crud on respective markdown notes files. +- Periods Tools: + - Period Tracking tools: can track cycles for a user. + - Mood tracker per cycle: Can save mood events in an ongoing cycle. + - Search: Can search through for events since the beginning of all tracking. +- Reminder Manager (Uses CALDAV): + - CRUD on Reminders: Manage reminders for a user. +- Scraper (currently disabled): Can scrape a given website for a given query. +- Youtube Tools: + - Summerization: Can summerize a youtube video. + - Searching in Video: Can search for a query in a youtube video. + - Download: Can download a youtube video. + +To install dependencies: + +```bash +bun install +``` + +To run: + +```bash +bun run index.ts +``` + +This project was created using `bun init` in bun v1.0.11. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime. diff --git a/assistant/system-prompts.ts b/assistant/system-prompts.ts new file mode 100644 index 0000000..1944187 --- /dev/null +++ b/assistant/system-prompts.ts @@ -0,0 +1,230 @@ +import { Message } from "../interfaces/message"; +import { format } from "date-fns"; +import { OpenAI } from "openai"; +import { getNotesSystemPrompt } from "../tools/notes"; +import { getReminderSystemPrompt } from "../tools/reminders"; +import { getCalendarSystemPrompt } from "../tools/calender"; +import { return_current_events } from "../tools/events"; +import { memory_manager_guide } from "../tools/memory-manager"; + +export async function buildSystemPrompts( + context_message: Message +): Promise { + const userRoles = context_message.getUserRoles(); + const model = "gpt-4o-mini"; + + const general_tools_notes: OpenAI.ChatCompletionSystemMessageParam[] = [ + { + role: "system", + content: `**Tool Notes:** + +1. For scraping direct download links from non-YouTube sites in \`code_interpreter\`, include these dependencies: + +\`\`\` +[packages] +aiohttp = "*" +python-socketio = "~=5.0" +yt-dlp = "*" +\`\`\` + +2. Use \`actions_manager\` to schedule actions for the user, like sending a message at a specific time or after a duration. +`, + }, + ]; + + const admin_system_messages: OpenAI.ChatCompletionSystemMessageParam[] = [ + { + role: "system", + content: `Your name is **Anya**. +You are an AI assistant helping **Raj** manage tasks (functionally JARVIS for Raj). + +Users interact with you via text or transcribed voice messages. + +Your current memories saved by Memory Manager: +--- +${memory_manager_guide("self")} +--- + +**Interaction Guidelines:** +- **Focused Responses:** Address user queries directly; avoid unnecessary information. +- **Brevity:** Keep responses concise and to the point. + +When context is provided inside a JSON message, it indicates a reply to the mentioned context. + +Always reply in plain text or markdown unless running a tool. +Ensure responses do not exceed 1500 characters. +`, + }, + { + role: "system", + content: `Current model being used: ${model}`, + }, + ...general_tools_notes, + { + role: "system", + content: `**Context for Casual Conversation:** +- Users are in India. +- Use 12-hour time format. +`, + }, + ]; + + const events = return_current_events().map((event) => event.eventId); + const creator_system_messages: OpenAI.ChatCompletionSystemMessageParam[] = [ + { + role: "system", + content: `You have access to **tool managers**. + +When using tool managers: + +- They may return extensive data; filter or summarize necessary information to provide what the user requested. +- Validate the manager's response to ensure it meets the user's needs. If not, refine your prompt and try again. +- Ensure your prompts to managers are clear and concise for desired outputs. + +**Important:** + +- Managers often maintain state across multiple calls, allowing for follow-up questions or additional information. +- Managers are specialized LLMs for specific tasks; they perform better with detailed prompts. +- Provide managers with as much detail as possible, e.g., user details when messaging someone specific. +`, + }, + { + role: "system", + content: `# **events_manager** +Use the event manager to listen to external events. + +- Each event can have multiple listeners, and each listener can have multiple actions. +- Use this manager when the user wants something to happen based on an event. + +**Examples:** +- When I get an email, format it. +- When I get home, turn on my room lights. +- Send me an email when I receive one from Pooja. +- Remind me to drink water at work. +- When I get a message on WhatsApp from Pooja, reply that I'm asleep. + +You can send these request directly to the event manager, you can add any more details if needed as you have more context about the user and conversation. + +**Available Events:** +${JSON.stringify(events)} + +# **actions_manager** +Use the actions manager to execute actions at a specific time or after a duration. + +- An action is a single instruction to execute at a specified time or after a duration. +- Use this manager when the user wants something to happen at a specific time or after a duration. +- When including tool names that maybe required for the action, ensure that you describe the tool's role in the action in detail. + +**Examples:** +- User: Send me a message at 6 PM. + Action Instruction: Notify user with some text at 6 PM. + Tool Names: none (no need to use any tool to notify the creator of the action) + +- User: Turn my Fan off every morning. + Action Instruction: Ask 'home_assistant_manager' to turn off the fan every morning. + Tool Names: ["home_assistant_manager"] + +- Every Evening, show me yesterday's gym stats. + Action Instruction: Fetch yesterday's gym stats by asking 'notes_manager' and send it to the user every evening around 6:30pm. + Tool Names: ["notes_manager"] + +- Tomorrow morning ping pooja that its an important day. + Action Instruction: Tomorrow morning 8am ask 'communication_manager' to send a message to Pooja that it's an important day. + Tool Names: ["communication_manager"] + +In both managers, use the \`communication_manager\` tool to send messages to other users on any platform. +`, + }, + ]; + + const regular_system_messages: OpenAI.ChatCompletionSystemMessageParam[] = [ + { + role: "system", + content: `Your name is **Anya**. +You are an AI that helps people in a server. + +Users interact with you via text or transcribed voice messages. + +**Interaction Guidelines:** +- **Focused Responses:** Address user queries directly; avoid unnecessary information. +- **Brevity:** Keep responses concise and to the point. + +When context is provided inside a JSON message, it indicates a reply to the mentioned context. + +Always reply in plain text or markdown unless running a tool. +Ensure responses do not exceed 1500 characters. +`, + }, + ...general_tools_notes, + { + role: "system", + content: `Current model being used: ${model}`, + }, + { + role: "system", + content: `**Context for Casual Conversation:** +- Users are in India. +- Use 12-hour time format. +`, + }, + ]; + + const menstrual_tracker_system_messages: OpenAI.ChatCompletionSystemMessageParam[] = + [ + { + role: "system", + content: `This is a private conversation between you and the user **${ + context_message.author.config?.name || context_message.author.username + }**. + +Your task is to help them track and manage their menstrual cycle. + +- Answer their queries and provide necessary information. +- Point out any irregularities and suggest possible causes, but **DO NOT DIAGNOSE**. + +**Current Date:** ${format(new Date(), "yyyy-MM-dd HH:mm:ss")} IST +`, + }, + ]; + + let final_system_messages: OpenAI.ChatCompletionMessageParam[] = []; + + // Determine which system messages to include based on user roles + if (userRoles.includes("admin")) { + final_system_messages = final_system_messages.concat(admin_system_messages); + } else { + final_system_messages = final_system_messages.concat( + regular_system_messages + ); + } + + if (userRoles.includes("menstrualUser")) { + final_system_messages = final_system_messages.concat( + menstrual_tracker_system_messages + ); + } + + if (userRoles.includes("creator")) { + final_system_messages = final_system_messages.concat( + creator_system_messages + ); + } + + const memory_prompt: OpenAI.ChatCompletionSystemMessageParam[] = [ + { + role: "system", + content: `**Note on Routing Memories:** + +Make sure to route memories to the appropriate managers by requesting the respective managers to 'remember' the memory. Here are some guidelines: +- All managers can save memories. Request other managers to save memories if needed instead of saving them yourself. +- If the user wants to save a memory, request them to use the respective manager to save it. +- If no other manager is appropriate, you can save the memory yourself. +- Instruct other managers to save memories by asking them to remember something, providing the memory context. +`, + }, + ]; + + final_system_messages = final_system_messages.concat(memory_prompt); + + return final_system_messages; +} diff --git a/bun.lockb b/bun.lockb new file mode 100755 index 0000000..f1f5542 Binary files /dev/null and b/bun.lockb differ diff --git a/config/index.ts b/config/index.ts new file mode 100644 index 0000000..2ab9ce1 --- /dev/null +++ b/config/index.ts @@ -0,0 +1,60 @@ +import fs from "fs"; +import { z } from "zod"; +import path from "path"; + +export const dataDir = path.join(process.env.ANYA_DIR || "./"); +export const pathInDataDir = (filename: string) => path.join(dataDir, filename); + +interface PlatformIdentity { + platform: "discord" | "whatsapp" | "email" | "events"; + id: string; // Platform-specific user ID +} + +export interface UserConfig { + name: string; + identities: PlatformIdentity[]; + relatives?: { + related_as: string[]; + user: UserConfig; + }[]; + roles: string[]; // Roles assigned to the user +} + +// Define Zod schemas for validation +const PlatformIdentitySchema = z.object({ + platform: z.enum(["discord", "whatsapp", "email", "events"]), + id: z.string(), +}); + +const UserConfigSchema: z.ZodType = z.lazy(() => + z.object({ + name: z.string(), + identities: z.array(PlatformIdentitySchema), + relatives: z + .array( + z.object({ + related_as: z.array(z.string()), + user: UserConfigSchema, // recursive schema for relatives + }) + ) + .optional(), + roles: z.array(z.string()), + }) +); + +// Schema for the full configuration file +const ConfigSchema = z.object({ + users: z.array(UserConfigSchema), + rolePermissions: z.record(z.string(), z.array(z.string())), +}); + +// Load user configuration data from file +const userConfigPath = pathInDataDir("user-config.json"); +const rawData = fs.readFileSync(userConfigPath, "utf-8"); +const parsedData = JSON.parse(rawData); + +// Validate the parsed JSON using the Zod schema +const configData = ConfigSchema.parse(parsedData); + +// Export the validated data +export const { users: userConfigs, rolePermissions } = configData; diff --git a/core/message-processor.ts b/core/message-processor.ts new file mode 100644 index 0000000..3b239aa --- /dev/null +++ b/core/message-processor.ts @@ -0,0 +1,440 @@ +import { PlatformAdapter } from "../interfaces/platform-adapter"; +import { Message, SentMessage } from "../interfaces/message"; +import { getTools, zodFunction } from "../tools"; +import OpenAI from "openai"; +import { createHash } from "crypto"; +import { format } from "date-fns"; +import { saveApiUsage } from "../usage"; +import { buildSystemPrompts } from "../assistant/system-prompts"; +import YAML from "yaml"; + +import { ask, get_transcription } from "../tools/ask"; +import { z } from "zod"; +import { send_sys_log } from "../interfaces/log"; + +interface MessageQueueEntry { + abortController: AbortController; + runningTools: boolean; +} + +export class MessageProcessor { + private openai: OpenAI; + private model: string = "gpt-4o-mini"; + private messageQueue: Map = new Map(); + private toolsCallMap: Map = + new Map(); + private channelIdHashMap: Map = new Map(); + private sentMessage: SentMessage | null = null; + + constructor(private adapter: PlatformAdapter) { + this.openai = new OpenAI({ + apiKey: process.env.OPENAI_API_KEY!, + }); + } + + public async processMessage(message: Message): Promise { + const userId = message.author.id; + const channelId = message.channelId || userId; // Use message.id if channelId is not available + + // Check if the message is a stop message + if (["stop", "reset"].includes(message.content.toLowerCase())) { + message.platform !== "whatsapp" && + (await message.send({ + content: "---setting this point as the start---", + })); + // Clear maps + const hashes = this.channelIdHashMap.get(channelId) ?? []; + hashes.forEach((hash) => { + this.toolsCallMap.delete(hash); + }); + this.channelIdHashMap.set(channelId, []); + return; + } + + if (this.messageQueue.has(channelId)) { + const queueEntry = this.messageQueue.get(channelId)!; + if (!queueEntry.runningTools) { + // Abort previous processing + queueEntry.abortController.abort(); + this.messageQueue.delete(channelId); + } else { + // If tools are running, do not abort and return + return; + } + } + + // Prepare OpenAI request + const abortController = new AbortController(); + this.messageQueue.set(channelId, { + abortController, + runningTools: false, + }); + + // Handle timeout + setTimeout(async () => { + const queueEntry = this.messageQueue.get(channelId); + if (queueEntry && !queueEntry.runningTools) { + abortController.abort(); + this.messageQueue.delete(channelId); + await message.send({ content: "Timed out." }); + } + }, 600000); // 10 minutes + + try { + // Indicate typing + message.platformAdapter.config.indicators.typing && + (await message.sendTyping()); + + // Fetch message history + const history = await this.adapter.fetchMessages(channelId, { + limit: 50, + }); + + // Send 'thinking...' indicator + if (message.platformAdapter.config.indicators.processing) + this.sentMessage = await message.send({ content: "thinking..." }); + + // Check for stop message in history + let stopIndex = -1; + for (let i = 0; i < history.length; i++) { + if ( + history[i].content === "---setting this point as the start---" || + history[i].content.replaceAll("!", "").trim() === "stop" + ) { + stopIndex = i; + break; + } + } + const effectiveHistory = + stopIndex !== -1 ? history.slice(0, stopIndex) : history; + + // Construct AI messages + const aiMessages = await this.constructAIMessages( + effectiveHistory, + message, + channelId + ); + + // Run tools and get AI response + const response = await this.runAI( + aiMessages as OpenAI.Chat.ChatCompletionMessage[], + message.author.username, + message, + abortController, + channelId + ); + + // Send reply via adapter + if (response && !response.includes("")) { + const content = this.isJsonParseable(response); + if (content && content.user_message) { + await message.send({ content: content.user_message }); + } else { + await message.send({ content: response }); + } + } + + // Delete the thinking message + if (this.sentMessage && this.sentMessage.deletable) { + await this.sentMessage.delete(); + } else if (this.sentMessage) { + // If not deletable, edit the message to indicate completion + await this.sentMessage.edit({ content: "Response sent." }); + } + } catch (error) { + console.error("Error processing message:", error); + await this.sentMessage?.delete(); + // await message.send({ + // content: "An error occurred while processing your message.", + // }); + } finally { + // Clean up + this.messageQueue.delete(channelId); + } + } + + private async constructAIMessages( + history: Message[], + message: Message, + channelId: string + ): Promise { + // Build system prompts based on user roles + const systemMessages: OpenAI.Chat.ChatCompletionMessageParam[] = + await buildSystemPrompts(message); + + // Map history messages to AI messages + const channelHashes = this.channelIdHashMap.get(channelId) || []; + + const aiMessagesArrays = await Promise.all( + history.reverse().map(async (msg) => { + const role = + msg.author.id === this.adapter.getBotId() ? "assistant" : "user"; + + // Process attachments + const files = (msg.attachments || []) + .filter((a) => !a.url.includes("voice-message.ogg")) + .map((a) => a.url); + + const embeds = (msg.embeds || []) + .map((e) => JSON.stringify(e)) + .join("\n"); + + // Transcribe voice messages + const voiceMessagesPromises = (msg.attachments || []) + .filter( + (a) => a.url.includes("voice-message.ogg") || a.type === "ptt" + ) + .map(async (a) => { + const data = + msg.platform === "whatsapp" ? (a.data as string) : a.url; + const binary = msg.platform === "whatsapp"; + const key = msg.platform === "whatsapp" ? msg.id : undefined; + return { + file: a.url, + transcription: await get_transcription(data, binary, key), + }; + }); + + const voiceMessages = await Promise.all(voiceMessagesPromises); + + // Process context message if any + let contextMessage = null; + if (msg.threadId) { + contextMessage = history.find((m) => m.id === msg.threadId); + // If not found, attempt to fetch it + if (!contextMessage) { + contextMessage = await this.adapter.fetchMessageById( + channelId, + msg.threadId + ); + } + } + + const contextAsJson = JSON.stringify({ + embeds: embeds || undefined, + files: files.length > 0 ? files : undefined, + user_message: msg.content, + user_voice_messages: + voiceMessages.length > 0 ? voiceMessages : undefined, + created_at: format(msg.timestamp, "yyyy-MM-dd HH:mm:ss") + " IST", + context_message: contextMessage + ? { + author: contextMessage.author.username, + created_at: + format(contextMessage.timestamp, "yyyy-MM-dd HH:mm:ss") + + " IST", + content: contextMessage.content, + } + : undefined, + context_files: + contextMessage?.attachments?.map((a) => a.url) || undefined, + context_embeds: + contextMessage?.embeds?.map((e) => JSON.stringify(e)).join("\n") || + undefined, + }); + + // get main user from userConfig + const user = this.adapter.getUserById(msg.author.id); + + const aiMessage: OpenAI.Chat.ChatCompletionMessageParam = { + role, + content: contextAsJson, + name: + user?.name || + msg.author.username.replace(/\s+/g, "_").substring(0, 64), + }; + + // Handle tool calls mapping if necessary + const hash = this.generateHash(msg.content); + const calls = this.toolsCallMap.get(hash); + if (calls) { + return [aiMessage, ...calls]; + } else { + return [aiMessage]; + } + }) + ); + + // Flatten aiMessages (since it's an array of arrays) + let aiMessages = aiMessagesArrays.flat(); + + // Collect hashes + history.forEach((msg) => { + const hash = this.generateHash(msg.content); + channelHashes.push(hash); + }); + + // Update the channelIdHashMap + this.channelIdHashMap.set(channelId, channelHashes); + + // If the conversation history is too long, summarize it + if (aiMessages.length > 25) { + aiMessages = await this.summarizeConversation(aiMessages); + } + + // Combine system messages and conversation messages + return systemMessages.concat(aiMessages); + } + + private async summarizeConversation( + messages: OpenAI.Chat.ChatCompletionMessageParam[] + ): Promise { + // Split the messages if necessary + const lastTen = messages.slice(-10); + const firstTen = messages.slice(0, 10); + + // Use the OpenAI API to generate the summary + const summaryResponse = await ask({ + model: "gpt-4o-mini", + prompt: `Summarize the below conversation into 2 sections: +1. General info about the conversation +2. Tools used in the conversation and their data in relation to the conversation. + +Conversation: +---- +${YAML.stringify(firstTen)} +---- + +Notes: +- Keep only important information and points, remove anything repetitive. +- Keep tools information if they are relevant. +- The summary is to give context about the conversation that was happening previously. +`, + }); + + const summaryContent = summaryResponse.choices[0].message.content; + + // Create a new conversation history with the summary + const summarizedConversation: OpenAI.Chat.ChatCompletionMessageParam[] = [ + { + role: "system", + content: `Previous messages summarized: +${summaryContent} +`, + }, + ...lastTen, + ]; + + return summarizedConversation; + } + + private async runAI( + messages: OpenAI.Chat.ChatCompletionMessage[], + username: string, + message: Message, + abortController: AbortController, + channelId: string + ): Promise { + const tmp = this; + + async function changeModel({ model }: { model: string }) { + tmp.model = model; + console.log("Model changed to", model); + return { message: "Model changed to " + model }; + } + + // Use OpenAI to get a response, include tools integration + const tools = getTools(username, message, "self"); + + const toolCalls: OpenAI.Chat.ChatCompletionMessageParam[] = []; + + console.log("Current Model", this.model); + const runner = this.openai.beta.chat.completions + .runTools( + { + model: this.model, + temperature: 0.6, + user: username, + messages, + stream: true, + tools: [ + zodFunction({ + name: "changeModel", + schema: z.object({ + model: z.string(z.enum(["gpt-4o-mini", "gpt-4o"])), + }), + function: changeModel, + description: `Change the model at run time. + Default Model is 'gpt-4o-mini'. + Current Model: ${this.model} + Switch to 'gpt-4o' before running any other tool. + Try to switch back to 'gpt-4o-mini' after running tools. + `, + }), + ...tools, + ], + }, + { signal: abortController.signal } + ) + .on("functionCall", async (fnc) => { + console.log("Function call:", fnc); + // Set runningTools to true + send_sys_log(`calling function: ${fnc.name}, in channel ${channelId}`); + const queueEntry = this.messageQueue.get(channelId); + + if (queueEntry) { + queueEntry.runningTools = true; + } + // Indicate running tools + if (this.sentMessage) { + await this.sentMessage.edit({ content: `Running ${fnc.name}...` }); + } else await message.send({ content: `Running ${fnc.name}...` }); + }) + .on("message", (m) => { + if ( + m.role === "assistant" && + (m.function_call || (m as any).tool_calls?.length) + ) { + toolCalls.push(m); + } + if ( + (m.role === "function" || m.role === "tool") && + ((m as any).function_call || (m as any).tool_call_id) + ) { + toolCalls.push(m); + } + }) + .on("error", (err) => { + console.error("Error:", err); + send_sys_log(`Error: ${err}, in channel ${channelId}`); + if (this.sentMessage) + this.sentMessage.edit({ content: "Error: " + JSON.stringify(err) }); + else message.send({ content: "Error: " + JSON.stringify(err) }); + }) + .on("abort", () => { + send_sys_log(`Aborting in channel ${channelId}`); + console.log("Aborted"); + }) + .on("totalUsage", (stat) => { + send_sys_log(`Usage: ${JSON.stringify(stat)}, in channel ${channelId}`); + saveApiUsage( + format(new Date(), "yyyy-MM-dd"), + this.model, + stat.prompt_tokens, + stat.completion_tokens + ); + }); + + const finalContent = await runner.finalContent(); + + // Store tool calls in toolsCallMap + const hash = this.generateHash(messages[messages.length - 1].content || ""); + this.toolsCallMap.set(hash, toolCalls); + + return finalContent ?? ""; + } + + private isJsonParseable(str: string) { + try { + return JSON.parse(str); + } catch (e) { + return false; + } + } + + private generateHash(input: string): string { + const hash = createHash("sha256"); + hash.update(input); + return hash.digest("hex"); + } +} diff --git a/env.sample b/env.sample new file mode 100644 index 0000000..90ac79c --- /dev/null +++ b/env.sample @@ -0,0 +1,40 @@ +GROQ_BASE_URL=https://api.groq.com/openai/v1 + +# OPENAI_API_KEY=example_openai_api_key + +ANYSCALE_TOKEN=example_anyscale_token +OPENAI_API_KEY=example_openai_api_key + +GROQ_API_KEY=example_groq_api_key + +DISCORD_BOT_TOKEN=example_discord_bot_token +DISCORD_CLIENT_ID=1186288013186179153 + +# Serp api token +SEARCH_API_KEY=example_search_api_key + +NEXTCLOUD_USERNAME=anya +NEXTCLOUD_PASSWORD=example_password +NEXTCLOUD_URL=https://cloud.tokio.space + +# points to link.raj.how instance +LINKWARDEN_API_KEY=example_linkwarden_api_key + +# points to git git.raj.how instance +GITEA_TOKEN=example_gitea_token + +NEXTCLOUD_USERNAME=raj +NEXTCLOUD_PASSWORD=example_password + +MINIO_ACCESS_KEY=example_minio_access_key +MINIO_SECRET_KEY=example_minio_secret_key + +RESEND_API_KEY=example_resend_api_key + +HA_KEY=example_ha_key + +EVENTS_PORT=6006 + +DISCORD_LOG_CHANNEL_ID=1177561269780363247 + +ANYA_DIR=./data \ No newline at end of file diff --git a/exp.ts b/exp.ts new file mode 100644 index 0000000..e69de29 diff --git a/index.ts b/index.ts new file mode 100644 index 0000000..7ff0a1c --- /dev/null +++ b/index.ts @@ -0,0 +1,3 @@ +import { startInterfaces } from "./interfaces"; + +startInterfaces(); diff --git a/interfaces/discord.ts b/interfaces/discord.ts new file mode 100644 index 0000000..474d02a --- /dev/null +++ b/interfaces/discord.ts @@ -0,0 +1,386 @@ +import { PlatformAdapter, FetchOptions } from "./platform-adapter"; +import { + Message as StdMessage, + SentMessage, + User as StdUser, + Attachment, + User, +} from "./message"; +import { + Client, + GatewayIntentBits, + Message as DiscordMessage, + TextChannel, + Partials, + ChannelType, + ActivityType, +} from "discord.js"; +import { UserConfig, userConfigs } from "../config"; + +export class DiscordAdapter implements PlatformAdapter { + private client: Client; + private botUserId: string = ""; + + public config = { + indicators: { + typing: true, + processing: true, + }, + }; + + constructor() { + this.client = new Client({ + intents: [ + GatewayIntentBits.Guilds, + GatewayIntentBits.GuildMessages, + GatewayIntentBits.MessageContent, + GatewayIntentBits.DirectMessages, + ], + partials: [Partials.Channel], + }); + + this.client.on("ready", () => { + console.log(`Logged in as ${this.client.user?.tag}!`); + this.botUserId = this.client.user?.id || ""; + this.client.user?.setActivity("as Human", { + type: Number(ActivityType.Playing), + }); + }); + + this.client.login(process.env.DISCORD_BOT_TOKEN); + } + + public getUserById(userId: string): UserConfig | null { + const userConfig = userConfigs.find((user) => + user.identities.some( + (identity) => identity.platform === "discord" && identity.id === userId + ) + ); + + if (!userConfig) { + return null; + } + + return userConfig; + } + + public onMessage(callback: (message: StdMessage) => void): void { + this.client.on("messageCreate", async (discordMessage: DiscordMessage) => { + if (discordMessage.author.bot) return; + + if (discordMessage.channel.type !== ChannelType.DM) { + return; + } + + // if user does not exist in userConfigs dont reply + const userConfig = this.getUserById(discordMessage.author.id); + if (!userConfig) { + return; + } + + const message = await this.convertMessage(discordMessage); + callback(message); + }); + } + + public async sendMessage(channelId: string, content: string): Promise { + const channel = await this.client.channels.fetch(channelId); + if ( + channel?.type !== ChannelType.GuildText && + channel?.type !== ChannelType.DM + ) { + console.error("Invalid channel type", channel?.type, channelId); + return; + } + await (channel as TextChannel).send(content); + } + public async fetchMessageById( + channelId: string, + messageId: string + ): Promise { + const channel = await this.client.channels.fetch(channelId); + if ( + !channel || + (channel.type !== ChannelType.GuildText && + channel.type !== ChannelType.DM) + ) { + throw new Error("Invalid channel type"); + } + + try { + const discordMessage = await (channel as TextChannel).messages.fetch( + messageId + ); + const stdMessage = await this.convertMessage(discordMessage); + return stdMessage; + } catch (error) { + console.error(`Failed to fetch message by ID: ${error}`); + return null; + } + } + public async fetchMessages( + channelId: string, + options: FetchOptions + ): Promise { + const channel = await this.client.channels.fetch(channelId); + if ( + !channel || + (channel.type !== ChannelType.GuildText && + channel.type !== ChannelType.DM) + ) { + throw new Error("Invalid channel type"); + } + + const messages = await (channel as TextChannel).messages.fetch({ + limit: options.limit || 10, + }); + const stdMessages: StdMessage[] = []; + + for (const msg of messages.values()) { + const stdMsg = await this.convertMessage(msg); + stdMessages.push(stdMsg); + } + + // Return messages in chronological order + return stdMessages; + } + + public getBotId(): string { + return this.botUserId; + } + + public async sendSystemLog(content: string) { + if (process.env.DISCORD_LOG_CHANNEL_ID) + return await this.sendMessage( + process.env.DISCORD_LOG_CHANNEL_ID || "", + content + ); + } + + public async searchUser(query: string): Promise { + const users = this.client.users.cache; + return users + .filter((user) => + user.username.toLowerCase().includes(query.toLowerCase()) + ) + .map((user) => ({ + id: user.id, + username: user.username, + config: this.getUserById(user.id), + })); + } + + // Method to create a Message interface for a user ID + public async createMessageInterface(userId: string): Promise { + try { + const user = await this.client.users.fetch(userId); + + console.log("creating message interface for: ", userId, user.username); + + const stdMessage: StdMessage = { + platform: "discord", + platformAdapter: this, + id: userId, + author: { + id: userId, + username: user.username, + config: this.getUserById(userId), + }, + content: "", + timestamp: new Date(), + channelId: "", + source: null, + threadId: undefined, + isDirectMessage: async () => true, + send: async (messageData) => { + const sentMessage = await user.send(messageData); + return this.convertSentMessage(sentMessage); + }, + reply: async (messageData) => { + const sentMessage = await user.send(messageData); + return this.convertSentMessage(sentMessage); + }, + getUserRoles: () => { + const userConfig = userConfigs.find((userConfig) => + userConfig.identities.some( + (identity) => + identity.platform === "discord" && identity.id === userId + ) + ); + return userConfig ? userConfig.roles : ["user"]; + }, + sendDirectMessage: async (userId, messageData) => { + const user = await this.client.users.fetch(userId); + console.log("sending message to: ", userId); + await user.send(messageData); + }, + sendMessageToChannel: async (channelId, messageData) => { + const channel = await this.client.channels.fetch(channelId); + if (channel?.isTextBased()) { + await (channel as TextChannel).send(messageData); + } + }, + fetchChannelMessages: async (limit: number) => { + const messages = await user.dmChannel?.messages.fetch({ limit }); + return Promise.all( + messages?.map((msg) => this.convertMessage(msg)) || [] + ); + }, + sendFile: async (fileUrl, fileName) => { + await user.dmChannel?.send({ + files: [{ attachment: fileUrl, name: fileName }], + }); + }, + sendTyping: async () => { + await user.dmChannel?.sendTyping(); + }, + }; + + return stdMessage; + } catch (error) { + throw new Error( + `Failed to create message interface for Discord user ${userId}: ${error}` + ); + } + } + + // You may also need to expose this method so it can be accessed elsewhere + public getMessageInterface = this.createMessageInterface; + + private async convertMessage( + discordMessage: DiscordMessage + ): Promise { + const stdUser: StdUser = { + id: discordMessage.author.id, + username: discordMessage.author.username, + config: this.getUserById(discordMessage.author.id), + }; + + const attachments: Attachment[] = discordMessage.attachments.map( + (attachment) => ({ + url: attachment.url, + contentType: attachment.contentType || undefined, + }) + ); + + const stdMessage: StdMessage = { + id: discordMessage.id, + content: discordMessage.content, + platformAdapter: this, + author: stdUser, + timestamp: discordMessage.createdAt, + channelId: discordMessage.channelId, + threadId: discordMessage.reference?.messageId || undefined, + source: discordMessage, + platform: "discord", + attachments, + isDirectMessage: async () => + discordMessage.channel.type === ChannelType.DM, + send: async (messageData) => { + const sentMessage = await discordMessage.channel.send(messageData); + return this.convertSentMessage(sentMessage); + }, + reply: async (messageData) => { + const sentMessage = await discordMessage.reply(messageData); + return this.convertSentMessage(sentMessage); + }, + getUserRoles: () => { + const userConfig = userConfigs.find((user) => + user.identities.some( + (identity) => + identity.platform === "discord" && + identity.id === discordMessage.author.id + ) + ); + return userConfig ? userConfig.roles : ["user"]; + }, + sendDirectMessage: async (userId, messageData) => { + const user = await this.client.users.fetch(userId); + await user.send(messageData); + }, + sendMessageToChannel: async (channelId, messageData) => { + const channel = await this.client.channels.fetch(channelId); + if (channel?.isTextBased()) { + await (channel as TextChannel).send(messageData); + } + }, + fetchChannelMessages: async (limit: number) => { + const messages = await discordMessage.channel.messages.fetch({ limit }); + return Promise.all(messages.map((msg) => this.convertMessage(msg))); + }, + sendFile: async (fileUrl, fileName) => { + await discordMessage.channel.send({ + files: [{ attachment: fileUrl, name: fileName }], + }); + }, + sendTyping: async () => { + await discordMessage.channel.sendTyping(); + }, + }; + + return stdMessage; + } + + private convertSentMessage(discordMessage: DiscordMessage): SentMessage { + return { + id: discordMessage.id, + platformAdapter: this, + content: discordMessage.content, + author: { + id: discordMessage.author.id, + username: discordMessage.author.username, + config: this.getUserById(discordMessage.author.id), + }, + timestamp: discordMessage.createdAt, + channelId: discordMessage.channelId, + threadId: discordMessage.reference?.messageId || undefined, + source: discordMessage, + platform: "discord", + deletable: discordMessage.deletable, + delete: async () => { + if (discordMessage.deletable) { + await discordMessage.delete(); + } + }, + edit: async (data) => { + await discordMessage.edit(data); + }, + getUserRoles: () => { + // Since this is a message sent by the bot, return bot's roles or empty array + return []; + }, + isDirectMessage: async () => + discordMessage.channel.type === ChannelType.DM, + sendDirectMessage: async (userId, messageData) => { + const user = await this.client.users.fetch(userId); + await user.send(messageData); + }, + sendMessageToChannel: async (channelId, messageData) => { + const channel = await this.client.channels.fetch(channelId); + if (channel?.isTextBased()) { + await (channel as TextChannel).send(messageData); + } + }, + fetchChannelMessages: async (limit: number) => { + const messages = await discordMessage.channel.messages.fetch({ limit }); + return Promise.all(messages.map((msg) => this.convertMessage(msg))); + }, + sendFile: async (fileUrl, fileName) => { + await discordMessage.channel.send({ + files: [{ attachment: fileUrl, name: fileName }], + }); + }, + sendTyping: async () => { + await discordMessage.channel.sendTyping(); + }, + reply: async (messageData) => { + const sentMessage = await discordMessage.reply(messageData); + return this.convertSentMessage(sentMessage); + }, + send: async (messageData) => { + const sentMessage = await discordMessage.channel.send(messageData); + return this.convertSentMessage(sentMessage); + }, + }; + } +} diff --git a/interfaces/events.ts b/interfaces/events.ts new file mode 100644 index 0000000..650d505 --- /dev/null +++ b/interfaces/events.ts @@ -0,0 +1,258 @@ +import { Elysia, t } from "elysia"; +import { userConfigs } from "../config"; +import { send_sys_log } from "./log"; + +// Define the type for the event callback +type EventCallback = ( + payload: Record +) => void | Record | Promise | Promise>; + +/** + * EventManager handles registration and emission of events based on event IDs. + */ +class EventManager { + private listeners: Map> = new Map(); + + /** + * Registers a new listener for a specific event ID. + * @param id - The event ID to listen for. + * @param callback - The callback to invoke when the event is emitted. + */ + on(id: string, callback: EventCallback): void { + if (!this.listeners.has(id)) { + this.listeners.set(id, new Set()); + } + this.listeners.get(id)!.add(callback); + } + + /** + * Removes a specific listener for a given event ID. + * @param id - The event ID. + * @param callback - The callback to remove. + */ + off(id: string, callback: EventCallback): void { + if (this.listeners.has(id)) { + this.listeners.get(id)?.delete(callback); + } + } + + /** + * Emits an event, triggering all registered listeners for the given event ID. + * This method does not wait for listeners to complete and does not collect their responses. + * @param id - The event ID to emit. + * @param payload - The payload to pass to the listeners. + */ + emit(id: string, payload: Record): void { + const callbacks = this.listeners.get(id); + if (callbacks) { + callbacks.forEach((cb) => { + try { + cb(payload); + } catch (error) { + console.error(`Error in listener for event '${id}':`, error); + } + }); + } + } + + /** + * Emits an event and waits for all listeners to complete. + * Collects and returns the responses from the listeners. + * @param id - The event ID to emit. + * @param payload - The payload to pass to the listeners. + * @returns An array of responses from the listeners. + */ + async emitWithResponse( + id: string, + payload: Record + ): Promise { + const callbacks = this.listeners.get(id); + const responses: any[] = []; + + if (callbacks) { + // Execute all callbacks and collect their responses + const promises = Array.from(callbacks).map(async (cb) => { + try { + const result = cb(payload); + if (result instanceof Promise) { + return await result; + } + return result; + } catch (error) { + console.error(`Error in listener for event '${id}':`, error); + return null; + } + }); + + const results = await Promise.all(promises); + // Filter out undefined or null responses + results.forEach((res) => { + if (res !== undefined && res !== null) { + responses.push(res); + } + }); + } + + return responses; + } +} + +// Instantiate the EventManager +const eventManager = new EventManager(); + +// Create the Elysia server +export const events = new Elysia() + .get("/", () => "Anya\nExternal event listener running") + .get( + "/events/:id", + async ({ params: { id }, query, headers }) => { + const wait = query.wait; + delete query.wait; + + if (id === "ping") { + console.log("Event received", query); + send_sys_log(`Ping event received: ${JSON.stringify(query)}`); + + if (wait) { + const responses = await eventManager.emitWithResponse( + "ping", + query as Record + ); + return { response: "pong", listeners: responses }; + } else { + eventManager.emit("ping", query as Record); + return "pong"; + } + } + + console.log("get hook", id); + console.log("Event received", query); + + if (!headers.token) { + return { error: "Unauthorized" }; + } + + const [username, password] = headers.token.split(":"); + const user = userConfigs.find((config) => config.name === username); + + if (!user) { + return { error: "Unauthorized" }; + } + + const found = user.identities.find( + (identity) => identity.platform === "events" && identity.id === password + ); + + // console.log("found", found); + if (!found) { + return { error: "Unauthorized" }; + } + + send_sys_log(`Event (${id}) received: ${JSON.stringify(query)}`); + + if (wait) { + const responses = await eventManager.emitWithResponse( + id, + query as Record + ); + return { response: "Event received", listeners: responses }; + } else { + eventManager.emit(id, query as Record); + return "Event received"; + } + }, + { + params: t.Object({ + id: t.String(), + }), + query: t.Object({ + wait: t.Optional(t.Boolean()), + }), + } + ) + .post( + "/events/:id", + async ({ params: { id }, body, headers, query }) => { + const wait = query.wait; + + console.log("post hook", id); + + // console.log("Event received", body); + // Handle ArrayBuffer body + if (body instanceof ArrayBuffer) { + const textbody = new TextDecoder().decode(body as ArrayBuffer); + try { + body = JSON.parse(textbody); + } catch (e) { + body = textbody; + } + } + // console.log("Event received", body); + + if (id === "ping") { + send_sys_log(`Ping event received: ${JSON.stringify(body)}`); + if (wait) { + const responses = await eventManager.emitWithResponse( + "ping", + body as Record + ); + return { response: "pong", listeners: responses }; + } else { + eventManager.emit("ping", body as Record); + return "pong"; + } + } + + if (!headers.token) { + return { error: "Unauthorized" }; + } + + const [username, password] = headers.token.split(":"); + const user = userConfigs.find((config) => config.name === username); + + if (!user) { + return { error: "Unauthorized" }; + } + + const found = user.identities.find( + (identity) => identity.platform === "events" && identity.id === password + ); + + if (!found) { + return { error: "Unauthorized" }; + } + + send_sys_log(`Event (${id}) received: ${JSON.stringify(body)}`); + + if (wait) { + const responses = await eventManager.emitWithResponse( + id, + body as Record + ); + return { responses: responses }; + } else { + eventManager.emit(id, body as Record); + return "Event received"; + } + }, + { + params: t.Object({ + id: t.String(), + }), + body: t.Any(), + query: t.Object({ + wait: t.Optional(t.Boolean()), + }), + } + ); + +// Function to start the server +export function startEventsServer() { + const port = parseInt(process.env.EVENTS_PORT || "7004", 10); + events.listen(port, () => { + console.log(`Events Server is running on port ${port}`); + }); +} + +// Export the eventManager to allow other modules to register listeners +export { eventManager }; diff --git a/interfaces/index.ts b/interfaces/index.ts new file mode 100644 index 0000000..a88c1b7 --- /dev/null +++ b/interfaces/index.ts @@ -0,0 +1,42 @@ +import { MessageProcessor } from "../core/message-processor"; +import { DiscordAdapter } from "./discord"; +import { startEventsServer } from "./events"; +import { Message } from "./message"; +import { WhatsAppAdapter } from "./whatsapp"; + +// Initialize Discord Adapter and Processor +export const discordAdapter = new DiscordAdapter(); + +const discordProcessor = new MessageProcessor(discordAdapter); + +// Initialize WhatsApp Adapter and Processor +export const whatsappAdapter = new WhatsAppAdapter(); +const whatsappProcessor = new MessageProcessor(whatsappAdapter); + +export function startInterfaces() { + discordAdapter.onMessage(async (message) => { + await discordProcessor.processMessage(message); + }); + whatsappAdapter.onMessage(async (message) => { + await whatsappProcessor.processMessage(message); + }); + startEventsServer(); +} + +export async function getMessageInterface(identity: { + platform: string; + id: string; +}): Promise { + try { + switch (identity.platform) { + case "discord": + return await discordAdapter.createMessageInterface(identity.id); + case "whatsapp": + return await whatsappAdapter.createMessageInterface(identity.id); + default: + throw new Error(`Unsupported platform: ${identity.platform}`); + } + } catch (error) { + throw new Error(`getMessageInterface error: ${(error as Error).message}`); + } +} diff --git a/interfaces/log.ts b/interfaces/log.ts new file mode 100644 index 0000000..04a2905 --- /dev/null +++ b/interfaces/log.ts @@ -0,0 +1,5 @@ +import { discordAdapter } from "."; + +export function send_sys_log(content: string) { + return discordAdapter.sendSystemLog(content); +} diff --git a/interfaces/message.ts b/interfaces/message.ts new file mode 100644 index 0000000..5ef32a8 --- /dev/null +++ b/interfaces/message.ts @@ -0,0 +1,65 @@ +import { UserConfig } from "../config"; +import { PlatformAdapter } from "./platform-adapter"; + +export interface User { + id: string; + username: string; + config?: UserConfig | null; + meta?: any; +} + +export interface SentMessage extends Message { + deletable: boolean; + delete: () => Promise; + edit: (data: any) => Promise; +} + +export interface Attachment { + url: string; + contentType?: string; + data?: Buffer | string; + type?: string; +} + +export interface Embed { + [key: string]: any; +} + +export interface MessageData { + content?: string; + embeds?: Embed[]; + file?: + | { + url: string; + } + | { path: string }; +} + +export interface Message { + id: string; + content: string; + author: User; + timestamp: Date; + channelId: string; + threadId?: string; + attachments?: Attachment[]; + embeds?: Embed[]; + source: any; // Original message object (from Discord or WhatsApp) + platform: "discord" | "whatsapp" | "other"; + reply: (data: MessageData) => Promise; + send: (data: MessageData) => Promise; + getUserRoles: () => string[]; + isDirectMessage: () => Promise; + sendDirectMessage: ( + userId: string, + messageData: MessageData + ) => Promise; + sendMessageToChannel: ( + channelId: string, + messageData: MessageData + ) => Promise; + sendFile: (fileUrl: string, fileName: string) => Promise; + fetchChannelMessages: (limit: number) => Promise; + sendTyping: () => Promise; + platformAdapter: PlatformAdapter; +} diff --git a/interfaces/platform-adapter.ts b/interfaces/platform-adapter.ts new file mode 100644 index 0000000..a109ecf --- /dev/null +++ b/interfaces/platform-adapter.ts @@ -0,0 +1,28 @@ +import { UserConfig } from "../config"; +import { Message, User } from "./message"; + +export interface FetchOptions { + limit?: number; + before?: string; + after?: string; +} + +export interface PlatformAdapter { + onMessage(callback: (message: Message) => void): void; + sendMessage(channelId: string, content: string): Promise; + fetchMessages(channelId: string, options: FetchOptions): Promise; + fetchMessageById( + channelId: string, + messageId: string + ): Promise; + getBotId(): string; // For identifying bot's own messages + getUserById(userId: string): UserConfig | null; + sendSystemLog?(content: string): Promise; + searchUser(query: string): Promise; + config: { + indicators: { + typing: boolean; + processing: boolean; + }; + }; +} diff --git a/interfaces/whatsapp.ts b/interfaces/whatsapp.ts new file mode 100644 index 0000000..c0b0a9e --- /dev/null +++ b/interfaces/whatsapp.ts @@ -0,0 +1,546 @@ +import { PlatformAdapter, FetchOptions } from "./platform-adapter"; +import { + Message as StdMessage, + User as StdUser, + SentMessage, + Attachment, +} from "./message"; +import { + Client as WAClient, + Message as WAMessage, + LocalAuth, + MessageMedia, +} from "whatsapp-web.js"; +import { UserConfig, userConfigs } from "../config"; +import { eventManager } from "./events"; +import { return_current_listeners } from "../tools/events"; +import Fuse from "fuse.js"; + +// const allowedUsers = ["pooja", "raj"]; +const allowedUsers: string[] = []; + +export class WhatsAppAdapter implements PlatformAdapter { + private client: WAClient; + private botUserId: string = "918884016724@c.us"; + + public config = { + indicators: { + typing: false, + processing: false, + }, + }; + + constructor() { + this.client = new WAClient({ + authStrategy: new LocalAuth(), + }); + try { + this.client.on("ready", () => { + console.log("WhatsApp Client is ready!"); + }); + + this.client.initialize(); + } catch (error) { + console.log(`Failed to initialize WhatsApp client: `, error); + } + } + public getUserById(userId: string): UserConfig | null { + const userConfig = userConfigs.find((user) => + user.identities.some( + (identity) => + identity.platform === "whatsapp" && `${identity.id}@c.us` === userId + ) + ); + + if (!userConfig) { + // console.log(`User not found for WhatsApp ID: ${userId}`); + return null; + } + + return userConfig; + } + + public onMessage(callback: (message: StdMessage) => void): void { + this.client.on("message_create", async (waMessage: WAMessage) => { + // emit internal event only if text message and there is an active listener + const listeners = return_current_listeners(); + if ( + typeof waMessage.body === "string" && + !waMessage.fromMe && + listeners.find((l) => l.eventId.includes("whatsapp")) + ) { + const contact = await this.client.getContactById(waMessage.from); + eventManager.emit("got_whatsapp_message", { + sender_id: waMessage.from, + sender_contact_name: + contact.name || contact.shortName || contact.pushname || "NA", + timestamp: waMessage.timestamp, + content: waMessage.body, + profile_image_url: await contact.getProfilePicUrl(), + is_group_message: contact.isGroup.toString(), + }); + } + + // user must exist in userConfigs + const usr = this.getUserById(waMessage.from); + if (!usr) { + console.log(`Ignoring ID: ${waMessage.from}`); + return; + } + + // user must be in allowedUsers + if (!allowedUsers.includes(usr.name)) { + // console.log(`User not allowed: ${usr.name}`); + return; + } + + // Ignore messages sent by the bot + if (waMessage.fromMe) return; + const message = await this.convertMessage(waMessage); + + callback(message); + }); + } + + public async sendMessage(channelId: string, content: string): Promise { + await this.client.sendMessage(channelId, content); + } + + public async fetchMessages( + channelId: string, + options: FetchOptions + ): Promise { + const chat = await this.client.getChatById(channelId); + const messages = await chat.fetchMessages({ limit: options.limit || 10 }); + + const stdMessages: StdMessage[] = []; + + for (const msg of messages) { + const stdMsg = await this.convertMessage(msg); + stdMessages.push(stdMsg); + } + + // Return messages in chronological order + return stdMessages.reverse(); + } + + public getBotId(): string { + return this.botUserId; + } + + public async createMessageInterface(userId: string): Promise { + try { + const contact = await this.client.getContactById(userId); + const stdMessage: StdMessage = { + platform: "whatsapp", + platformAdapter: this, + id: userId, + author: { + id: userId, + username: + contact.name || contact.shortName || contact.pushname || "NA", + config: this.getUserById(userId), + }, + content: "", // Placeholder content + timestamp: new Date(), // Placeholder timestamp + channelId: userId, // Assuming userId is the channelId + source: null, // Placeholder source + threadId: undefined, // Placeholder threadId + isDirectMessage: async () => true, + sendDirectMessage: async (recipientId, messageData) => { + const tcontact = await this.client.getContactById(recipientId); + const tchat = await tcontact.getChat(); + let media; + if (messageData.file && "url" in messageData.file) { + media = await MessageMedia.fromUrl(messageData.file.url); + } + if (messageData.file && "path" in messageData.file) { + media = MessageMedia.fromFilePath(messageData.file.path); + } + + await tchat.sendMessage(messageData.content || "", { media }); + }, + sendMessageToChannel: async (channelId, messageData) => { + let media; + if (messageData.file && "url" in messageData.file) { + media = await MessageMedia.fromUrl(messageData.file.url); + } + if (messageData.file && "path" in messageData.file) { + media = MessageMedia.fromFilePath(messageData.file.path); + } + await this.client.sendMessage(channelId, messageData.content || "", { + media, + }); + }, + sendFile: async (fileUrl, fileName) => { + const media = MessageMedia.fromFilePath(fileUrl); + await this.client.sendMessage(userId, media, { + caption: fileName, + }); + }, + fetchChannelMessages: async (limit: number) => { + const chat = await this.client.getChatById(userId); + const messages = await chat.fetchMessages({ limit }); + return Promise.all(messages.map((msg) => this.convertMessage(msg))); + }, + getUserRoles: () => { + const userConfig = userConfigs.find((user) => + user.identities.some( + (identity) => + identity.platform === "whatsapp" && identity.id === userId + ) + ); + return userConfig ? userConfig.roles : ["user"]; + }, + send: async (messageData) => { + let media; + if (messageData.file && "url" in messageData.file) { + media = await MessageMedia.fromUrl(messageData.file.url); + } + if (messageData.file && "path" in messageData.file) { + media = MessageMedia.fromFilePath(messageData.file.path); + } + const sentMessage = await this.client.sendMessage( + userId, + messageData.content || "", + { + media, + } + ); + return this.convertSentMessage(sentMessage); + }, + reply: async (messageData) => { + let media; + if (messageData.file && "url" in messageData.file) { + media = await MessageMedia.fromUrl(messageData.file.url); + } + if (messageData.file && "path" in messageData.file) { + media = MessageMedia.fromFilePath(messageData.file.path); + } + + const sentMessage = await this.client.sendMessage( + userId, + messageData.content || "", + { + media, + } + ); + return this.convertSentMessage(sentMessage); + }, + sendTyping: async () => { + // WhatsApp Web API does not support sending typing indicators directly + // This method can be left as a no-op or you can implement a workaround if possible + }, + }; + + return stdMessage; + } catch (error) { + throw new Error( + `Failed to create message interface for WhatsApp user ${userId}: ${error}` + ); + } + } + async searchUser(query: string): Promise { + try { + const contacts = await this.client.getContacts(); + + const stdcontacts = await Promise.all( + contacts + .filter((c) => c.isMyContact) + .map(async (contact) => { + return { + id: contact.id._serialized, + username: + contact.pushname || contact.name || contact.shortName || "NA", + config: this.getUserById(contact.id._serialized), + meta: { + about: contact.getAbout(), + verifiedName: contact.verifiedName, + shortName: contact.shortName, + pushname: contact.pushname, + name: contact.name, + profilePicUrl: await contact.getProfilePicUrl(), + }, + }; + }) + ); + + console.log("Starting search"); + const fuse = new Fuse(stdcontacts, { + keys: ["id", "username"], + threshold: 0.3, + }); + const results = fuse.search(query); + console.log("search done", results.length); + return results.map((result) => result.item); + } catch (error) { + throw new Error(`Failed to search for WhatsApp contacts: ${error}`); + } + } + // Expose this method so it can be accessed elsewhere + public getMessageInterface = this.createMessageInterface; + + private async convertMessage(waMessage: WAMessage): Promise { + const contact = await waMessage.getContact(); + + const stdUser: StdUser = { + id: contact.id._serialized, + username: contact.name || contact.shortName || contact.pushname || "NA", + config: this.getUserById(contact.id._serialized), + }; + + // Convert attachments + let attachments: Attachment[] = []; + if (waMessage.hasMedia) { + const media = await waMessage.downloadMedia(); + + attachments.push({ + url: "", // WhatsApp does not provide a direct URL to the media + data: media.data, + contentType: media.mimetype, + type: waMessage.type, + }); + } + + const stdMessage: StdMessage = { + id: waMessage.id._serialized, + content: waMessage.body, + platformAdapter: this, + author: stdUser, + timestamp: new Date(waMessage.timestamp * 1000), + channelId: waMessage.from, + threadId: waMessage.hasQuotedMsg + ? (await waMessage.getQuotedMessage()).id._serialized + : undefined, + source: waMessage, + platform: "whatsapp", + isDirectMessage: async () => { + const chat = await this.client.getChatById(waMessage.from); + return !chat.isGroup; // Returns true if not a group chat + }, + sendDirectMessage: async (recipientId, messageData) => { + let media; + if (messageData.file && "url" in messageData.file) { + media = await MessageMedia.fromUrl(messageData.file.url); + } + if (messageData.file && "path" in messageData.file) { + media = MessageMedia.fromFilePath(messageData.file.path); + } + await this.client.sendMessage(recipientId, messageData.content || "", { + media, + }); + }, + sendMessageToChannel: async (channelId, messageData) => { + let media; + if (messageData.file && "url" in messageData.file) { + media = await MessageMedia.fromUrl(messageData.file.url); + } + if (messageData.file && "path" in messageData.file) { + media = MessageMedia.fromFilePath(messageData.file.path); + } + await this.client.sendMessage(channelId, messageData.content || "", { + media, + }); + }, + sendFile: async (fileUrl, fileName) => { + const media = MessageMedia.fromFilePath(fileUrl); + await this.client.sendMessage(waMessage.from, media, { + caption: fileName, + }); + }, + fetchChannelMessages: async (limit: number) => { + const chat = await this.client.getChatById(waMessage.from); + const messages = await chat.fetchMessages({ limit }); + return Promise.all(messages.map((msg) => this.convertMessage(msg))); + }, + getUserRoles: () => { + const userConfig = userConfigs.find((user) => + user.identities.some( + (identity) => + identity.platform === "whatsapp" && + identity.id === contact.id._serialized + ) + ); + return userConfig ? userConfig.roles : ["user"]; + }, + send: async (messageData) => { + let media; + if (messageData.file && "url" in messageData.file) { + media = await MessageMedia.fromUrl(messageData.file.url); + } + if (messageData.file && "path" in messageData.file) { + media = MessageMedia.fromFilePath(messageData.file.path); + } + const sentMessage = await this.client.sendMessage( + waMessage.from, + messageData.content || "", + { + media, + } + ); + return this.convertSentMessage(sentMessage); + }, + reply: async (messageData) => { + let media; + if (messageData.file && "url" in messageData.file) { + media = await MessageMedia.fromUrl(messageData.file.url); + } + if (messageData.file && "path" in messageData.file) { + media = MessageMedia.fromFilePath(messageData.file.path); + } + const sentMessage = await this.client.sendMessage( + waMessage.from, + messageData.content || "", + { + media, + } + ); + return this.convertSentMessage(sentMessage); + }, + sendTyping: async () => { + // WhatsApp Web API does not support sending typing indicators directly + // You may leave this as a no-op + }, + }; + + return stdMessage; + } + + public async fetchMessageById( + channelId: string, + messageId: string + ): Promise { + try { + const waMessage = await this.client.getMessageById(messageId); + if (waMessage) { + const stdMessage = await this.convertMessage(waMessage); + return stdMessage; + } else { + return null; + } + } catch (error) { + console.error(`Failed to fetch message by ID: ${error}`); + return null; + } + } + + private async convertSentMessage( + sentWAMessage: WAMessage + ): Promise { + const contact = await sentWAMessage.getContact(); + + return { + id: sentWAMessage.id._serialized, + platformAdapter: this, + content: sentWAMessage.body, + author: { + id: contact.id._serialized, + username: + contact.name || + contact.shortName || + contact.pushname || + contact.number, + config: this.getUserById(contact.id._serialized), + }, + timestamp: new Date(sentWAMessage.timestamp * 1000), + channelId: sentWAMessage.from, + threadId: sentWAMessage.hasQuotedMsg + ? (await sentWAMessage.getQuotedMessage()).id._serialized + : undefined, + source: sentWAMessage, + platform: "whatsapp", + deletable: true, + delete: async () => { + await sentWAMessage.delete(); + }, + edit: async (messageData) => { + sentWAMessage.edit(messageData.content || ""); + }, + reply: async (messageData) => { + let media; + if (messageData.file && "url" in messageData.file) { + media = await MessageMedia.fromUrl(messageData.file.url); + } + if (messageData.file && "path" in messageData.file) { + media = MessageMedia.fromFilePath(messageData.file.path); + } + const replyMessage = await sentWAMessage.reply( + messageData.content || "", + sentWAMessage.id._serialized, + { media } + ); + return this.convertSentMessage(replyMessage); + }, + send: async (messageData) => { + let media; + if (messageData.file && "url" in messageData.file) { + media = await MessageMedia.fromUrl(messageData.file.url); + } + if (messageData.file && "path" in messageData.file) { + media = MessageMedia.fromFilePath(messageData.file.path); + } + const sentMessage = await this.client.sendMessage( + sentWAMessage.from, + messageData.content || "", + { + media, + } + ); + return this.convertSentMessage(sentMessage); + }, + getUserRoles: () => { + const userConfig = userConfigs.find((user) => + user.identities.some( + (identity) => + identity.platform === "whatsapp" && + identity.id === contact.id._serialized + ) + ); + return userConfig ? userConfig.roles : ["user"]; + }, + isDirectMessage: async () => { + const chat = await this.client.getChatById(sentWAMessage.from); + return !chat.isGroup; // Returns true if not a group chat + }, + sendDirectMessage: async (recipientId, messageData) => { + let media; + if (messageData.file && "url" in messageData.file) { + media = await MessageMedia.fromUrl(messageData.file.url); + } + if (messageData.file && "path" in messageData.file) { + media = MessageMedia.fromFilePath(messageData.file.path); + } + await this.client.sendMessage(recipientId, messageData.content || "", { + media, + }); + }, + sendMessageToChannel: async (channelId, messageData) => { + let media; + if (messageData.file && "url" in messageData.file) { + media = await MessageMedia.fromUrl(messageData.file.url); + } + if (messageData.file && "path" in messageData.file) { + media = MessageMedia.fromFilePath(messageData.file.path); + } + await this.client.sendMessage(channelId, messageData.content || "", { + media, + }); + }, + sendFile: async (fileUrl, fileName) => { + const media = MessageMedia.fromFilePath(fileUrl); + await this.client.sendMessage(sentWAMessage.from, media, { + caption: fileName, + }); + }, + fetchChannelMessages: async (limit: number) => { + const chat = await this.client.getChatById(sentWAMessage.from); + const messages = await chat.fetchMessages({ limit }); + return Promise.all(messages.map((msg) => this.convertMessage(msg))); + }, + sendTyping: async () => { + // WhatsApp Web API does not support sending typing indicators directly + // You may leave this as a no-op + }, + }; + } +} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..aa351c7 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,9821 @@ +{ + "name": "anya", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "anya", + "hasInstallScript": true, + "dependencies": { + "@dqbd/tiktoken": "^1.0.15", + "@nextcloud/files": "^3.8.0", + "@solyarisoftware/voskjs": "^1.2.8", + "@types/node-cron": "^3.0.11", + "@types/turndown": "^5.0.5", + "@types/xml2js": "^0.4.14", + "axios": "^1.7.3", + "cheerio": "^1.0.0-rc.12", + "date-fns": "^3.6.0", + "discord.js": "^14.14.1", + "elysia": "^1.1.17", + "fluent-ffmpeg": "^2.1.3", + "form-data": "^4.0.0", + "fuse.js": "^7.0.0", + "fuzzysort": "^3.0.2", + "i": "^0.3.7", + "langchain": "^0.0.212", + "mathjs": "^12.2.1", + "meta-fetcher": "^3.1.1", + "minio": "^8.0.1", + "nanoid": "^5.0.4", + "nextcloud-node-client": "^1.8.1", + "node-cron": "^3.0.3", + "npm": "^10.2.5", + "openai": "^4.54.0", + "pyodide": "^0.24.1", + "qrcode-terminal": "^0.12.0", + "quickchart-js": "^3.1.3", + "resend": "^4.0.0", + "serpapi": "^2.0.0", + "turndown": "^7.2.0", + "whatsapp-web.js": "^1.26.0", + "whisper-node": "^1.1.1", + "xml2js": "^0.6.2", + "youtube-transcript": "^1.2.1", + "youtubei.js": "^5.8.0", + "ytdl-core": "^4.11.5", + "zod": "^3.22.4", + "zod-to-json-schema": "^3.23.0", + "zx": "^7.2.3" + }, + "devDependencies": { + "@types/fluent-ffmpeg": "^2.1.24", + "bun-types": "latest" + }, + "peerDependencies": { + "typescript": "^5.0.0" + } + }, + "node_modules/@anthropic-ai/sdk": { + "version": "0.9.1", + "license": "MIT", + "dependencies": { + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "digest-fetch": "^1.3.0", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7", + "web-streams-polyfill": "^3.2.1" + } + }, + "node_modules/@anthropic-ai/sdk/node_modules/@types/node": { + "version": "18.19.33", + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.25.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.25.7.tgz", + "integrity": "sha512-0xZJFNE5XMpENsgfHYTw8FbX4kv53mFLn2i3XPoq69LyhYSCBJtitaHx9QnsVTrsogI4Z3+HtEfZ2/GFPOtf5g==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@babel/highlight": "^7.25.7", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.25.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.25.7.tgz", + "integrity": "sha512-AM6TzwYqGChO45oiuPqwL2t20/HdMC1rTPAesnBCgPCSF1x3oN9MVUwQV2iyz4xqWrctwK5RNC8LV22kaQCNYg==", + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight": { + "version": "7.25.7", + "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.25.7.tgz", + "integrity": "sha512-iYyACpW3iW8Fw+ZybQK+drQre+ns/tKpXbNESfrhNnPLIklLbXr7MYJ6gPEd0iETGLOK+SxMjVvKb/ffmk+FEw==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@babel/helper-validator-identifier": "^7.25.7", + "chalk": "^2.4.2", + "js-tokens": "^4.0.0", + "picocolors": "^1.0.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/highlight/node_modules/ansi-styles": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", + "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "color-convert": "^1.9.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/chalk": { + "version": "2.4.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", + "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "ansi-styles": "^3.2.1", + "escape-string-regexp": "^1.0.5", + "supports-color": "^5.3.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/highlight/node_modules/color-convert": { + "version": "1.9.3", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", + "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "color-name": "1.1.3" + } + }, + "node_modules/@babel/highlight/node_modules/color-name": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", + "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/@babel/highlight/node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/@babel/runtime": { + "version": "7.25.7", + "license": "MIT", + "dependencies": { + "regenerator-runtime": "^0.14.0" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@buttercup/fetch": { + "version": "0.2.1", + "license": "MIT", + "optionalDependencies": { + "node-fetch": "^3.3.0" + } + }, + "node_modules/@buttercup/fetch/node_modules/node-fetch": { + "version": "3.3.2", + "license": "MIT", + "optional": true, + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/@discordjs/builders": { + "version": "1.9.0", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/formatters": "^0.5.0", + "@discordjs/util": "^1.1.1", + "@sapphire/shapeshift": "^4.0.0", + "discord-api-types": "0.37.97", + "fast-deep-equal": "^3.1.3", + "ts-mixer": "^6.0.4", + "tslib": "^2.6.3" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/builders/node_modules/discord-api-types": { + "version": "0.37.97", + "license": "MIT" + }, + "node_modules/@discordjs/collection": { + "version": "1.5.3", + "license": "Apache-2.0", + "engines": { + "node": ">=16.11.0" + } + }, + "node_modules/@discordjs/formatters": { + "version": "0.5.0", + "license": "Apache-2.0", + "dependencies": { + "discord-api-types": "0.37.97" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/formatters/node_modules/discord-api-types": { + "version": "0.37.97", + "license": "MIT" + }, + "node_modules/@discordjs/rest": { + "version": "2.4.0", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/collection": "^2.1.1", + "@discordjs/util": "^1.1.1", + "@sapphire/async-queue": "^1.5.3", + "@sapphire/snowflake": "^3.5.3", + "@vladfrangu/async_event_emitter": "^2.4.6", + "discord-api-types": "0.37.97", + "magic-bytes.js": "^1.10.0", + "tslib": "^2.6.3", + "undici": "6.19.8" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/rest/node_modules/@discordjs/collection": { + "version": "2.1.1", + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/rest/node_modules/discord-api-types": { + "version": "0.37.97", + "license": "MIT" + }, + "node_modules/@discordjs/util": { + "version": "1.1.1", + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/ws": { + "version": "1.1.1", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/collection": "^2.1.0", + "@discordjs/rest": "^2.3.0", + "@discordjs/util": "^1.1.0", + "@sapphire/async-queue": "^1.5.2", + "@types/ws": "^8.5.10", + "@vladfrangu/async_event_emitter": "^2.2.4", + "discord-api-types": "0.37.83", + "tslib": "^2.6.2", + "ws": "^8.16.0" + }, + "engines": { + "node": ">=16.11.0" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/ws/node_modules/@discordjs/collection": { + "version": "2.1.1", + "license": "Apache-2.0", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/@discordjs/ws/node_modules/discord-api-types": { + "version": "0.37.83", + "license": "MIT" + }, + "node_modules/@discordjs/ws/node_modules/ws": { + "version": "8.18.0", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/@dqbd/tiktoken": { + "version": "1.0.17", + "license": "MIT" + }, + "node_modules/@fastify/busboy": { + "version": "2.1.1", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/@isaacs/cliui": { + "version": "8.0.2", + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@isaacs/cliui/node_modules/string-width/node_modules/emoji-regex": { + "version": "9.2.2", + "license": "MIT" + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/@isaacs/cliui/node_modules/strip-ansi/node_modules/ansi-regex": { + "version": "6.0.1", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/@langchain/community": { + "version": "0.0.57", + "license": "MIT", + "dependencies": { + "@langchain/core": "~0.1.60", + "@langchain/openai": "~0.0.28", + "expr-eval": "^2.0.2", + "flat": "^5.0.2", + "langsmith": "~0.1.1", + "uuid": "^9.0.0", + "zod": "^3.22.3", + "zod-to-json-schema": "^3.22.5" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@aws-crypto/sha256-js": "^5.0.0", + "@aws-sdk/client-bedrock-agent-runtime": "^3.485.0", + "@aws-sdk/client-bedrock-runtime": "^3.422.0", + "@aws-sdk/client-dynamodb": "^3.310.0", + "@aws-sdk/client-kendra": "^3.352.0", + "@aws-sdk/client-lambda": "^3.310.0", + "@aws-sdk/client-sagemaker-runtime": "^3.310.0", + "@aws-sdk/client-sfn": "^3.310.0", + "@aws-sdk/credential-provider-node": "^3.388.0", + "@azure/search-documents": "^12.0.0", + "@clickhouse/client": "^0.2.5", + "@cloudflare/ai": "*", + "@datastax/astra-db-ts": "^1.0.0", + "@elastic/elasticsearch": "^8.4.0", + "@getmetal/metal-sdk": "*", + "@getzep/zep-js": "^0.9.0", + "@gomomento/sdk": "^1.51.1", + "@gomomento/sdk-core": "^1.51.1", + "@google-ai/generativelanguage": "^0.2.1", + "@gradientai/nodejs-sdk": "^1.2.0", + "@huggingface/inference": "^2.6.4", + "@mlc-ai/web-llm": "^0.2.35", + "@mozilla/readability": "*", + "@neondatabase/serverless": "*", + "@opensearch-project/opensearch": "*", + "@pinecone-database/pinecone": "*", + "@planetscale/database": "^1.8.0", + "@premai/prem-sdk": "^0.3.25", + "@qdrant/js-client-rest": "^1.8.2", + "@raycast/api": "^1.55.2", + "@rockset/client": "^0.9.1", + "@smithy/eventstream-codec": "^2.0.5", + "@smithy/protocol-http": "^3.0.6", + "@smithy/signature-v4": "^2.0.10", + "@smithy/util-utf8": "^2.0.0", + "@supabase/postgrest-js": "^1.1.1", + "@supabase/supabase-js": "^2.10.0", + "@tensorflow-models/universal-sentence-encoder": "*", + "@tensorflow/tfjs-converter": "*", + "@tensorflow/tfjs-core": "*", + "@upstash/redis": "^1.20.6", + "@upstash/vector": "^1.0.7", + "@vercel/kv": "^0.2.3", + "@vercel/postgres": "^0.5.0", + "@writerai/writer-sdk": "^0.40.2", + "@xata.io/client": "^0.28.0", + "@xenova/transformers": "^2.5.4", + "@zilliz/milvus2-sdk-node": ">=2.2.7", + "better-sqlite3": "^9.4.0", + "cassandra-driver": "^4.7.2", + "cborg": "^4.1.1", + "chromadb": "*", + "closevector-common": "0.1.3", + "closevector-node": "0.1.6", + "closevector-web": "0.1.6", + "cohere-ai": "*", + "convex": "^1.3.1", + "couchbase": "^4.3.0", + "discord.js": "^14.14.1", + "dria": "^0.0.3", + "duck-duck-scrape": "^2.2.5", + "faiss-node": "^0.5.1", + "firebase-admin": "^11.9.0 || ^12.0.0", + "google-auth-library": "^8.9.0", + "googleapis": "^126.0.1", + "hnswlib-node": "^3.0.0", + "html-to-text": "^9.0.5", + "interface-datastore": "^8.2.11", + "ioredis": "^5.3.2", + "it-all": "^3.0.4", + "jsdom": "*", + "jsonwebtoken": "^9.0.2", + "llmonitor": "^0.5.9", + "lodash": "^4.17.21", + "lunary": "^0.6.11", + "mongodb": ">=5.2.0", + "mysql2": "^3.3.3", + "neo4j-driver": "*", + "node-llama-cpp": "*", + "pg": "^8.11.0", + "pg-copy-streams": "^6.0.5", + "pickleparser": "^0.2.1", + "portkey-ai": "^0.1.11", + "redis": "*", + "replicate": "^0.18.0", + "typeorm": "^0.3.12", + "typesense": "^1.5.3", + "usearch": "^1.1.1", + "vectordb": "^0.1.4", + "voy-search": "0.6.2", + "weaviate-ts-client": "*", + "web-auth-library": "^1.0.3", + "ws": "^8.14.2" + }, + "peerDependenciesMeta": { + "@aws-crypto/sha256-js": { + "optional": true + }, + "@aws-sdk/client-bedrock-agent-runtime": { + "optional": true + }, + "@aws-sdk/client-bedrock-runtime": { + "optional": true + }, + "@aws-sdk/client-dynamodb": { + "optional": true + }, + "@aws-sdk/client-kendra": { + "optional": true + }, + "@aws-sdk/client-lambda": { + "optional": true + }, + "@aws-sdk/client-sagemaker-runtime": { + "optional": true + }, + "@aws-sdk/client-sfn": { + "optional": true + }, + "@aws-sdk/credential-provider-node": { + "optional": true + }, + "@azure/search-documents": { + "optional": true + }, + "@clickhouse/client": { + "optional": true + }, + "@cloudflare/ai": { + "optional": true + }, + "@datastax/astra-db-ts": { + "optional": true + }, + "@elastic/elasticsearch": { + "optional": true + }, + "@getmetal/metal-sdk": { + "optional": true + }, + "@getzep/zep-js": { + "optional": true + }, + "@gomomento/sdk": { + "optional": true + }, + "@gomomento/sdk-core": { + "optional": true + }, + "@google-ai/generativelanguage": { + "optional": true + }, + "@gradientai/nodejs-sdk": { + "optional": true + }, + "@huggingface/inference": { + "optional": true + }, + "@mlc-ai/web-llm": { + "optional": true + }, + "@mozilla/readability": { + "optional": true + }, + "@neondatabase/serverless": { + "optional": true + }, + "@opensearch-project/opensearch": { + "optional": true + }, + "@pinecone-database/pinecone": { + "optional": true + }, + "@planetscale/database": { + "optional": true + }, + "@premai/prem-sdk": { + "optional": true + }, + "@qdrant/js-client-rest": { + "optional": true + }, + "@raycast/api": { + "optional": true + }, + "@rockset/client": { + "optional": true + }, + "@smithy/eventstream-codec": { + "optional": true + }, + "@smithy/protocol-http": { + "optional": true + }, + "@smithy/signature-v4": { + "optional": true + }, + "@smithy/util-utf8": { + "optional": true + }, + "@supabase/postgrest-js": { + "optional": true + }, + "@supabase/supabase-js": { + "optional": true + }, + "@tensorflow-models/universal-sentence-encoder": { + "optional": true + }, + "@tensorflow/tfjs-converter": { + "optional": true + }, + "@tensorflow/tfjs-core": { + "optional": true + }, + "@upstash/redis": { + "optional": true + }, + "@upstash/vector": { + "optional": true + }, + "@vercel/kv": { + "optional": true + }, + "@vercel/postgres": { + "optional": true + }, + "@writerai/writer-sdk": { + "optional": true + }, + "@xata.io/client": { + "optional": true + }, + "@xenova/transformers": { + "optional": true + }, + "@zilliz/milvus2-sdk-node": { + "optional": true + }, + "better-sqlite3": { + "optional": true + }, + "cassandra-driver": { + "optional": true + }, + "cborg": { + "optional": true + }, + "chromadb": { + "optional": true + }, + "closevector-common": { + "optional": true + }, + "closevector-node": { + "optional": true + }, + "closevector-web": { + "optional": true + }, + "cohere-ai": { + "optional": true + }, + "convex": { + "optional": true + }, + "couchbase": { + "optional": true + }, + "discord.js": { + "optional": true + }, + "dria": { + "optional": true + }, + "duck-duck-scrape": { + "optional": true + }, + "faiss-node": { + "optional": true + }, + "firebase-admin": { + "optional": true + }, + "google-auth-library": { + "optional": true + }, + "googleapis": { + "optional": true + }, + "hnswlib-node": { + "optional": true + }, + "html-to-text": { + "optional": true + }, + "interface-datastore": { + "optional": true + }, + "ioredis": { + "optional": true + }, + "it-all": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "jsonwebtoken": { + "optional": true + }, + "llmonitor": { + "optional": true + }, + "lodash": { + "optional": true + }, + "lunary": { + "optional": true + }, + "mongodb": { + "optional": true + }, + "mysql2": { + "optional": true + }, + "neo4j-driver": { + "optional": true + }, + "node-llama-cpp": { + "optional": true + }, + "pg": { + "optional": true + }, + "pg-copy-streams": { + "optional": true + }, + "pickleparser": { + "optional": true + }, + "portkey-ai": { + "optional": true + }, + "redis": { + "optional": true + }, + "replicate": { + "optional": true + }, + "typeorm": { + "optional": true + }, + "typesense": { + "optional": true + }, + "usearch": { + "optional": true + }, + "vectordb": { + "optional": true + }, + "voy-search": { + "optional": true + }, + "weaviate-ts-client": { + "optional": true + }, + "web-auth-library": { + "optional": true + }, + "ws": { + "optional": true + } + } + }, + "node_modules/@langchain/community/node_modules/langsmith": { + "version": "0.1.30", + "license": "MIT", + "dependencies": { + "@types/uuid": "^9.0.1", + "commander": "^10.0.1", + "p-queue": "^6.6.2", + "p-retry": "4", + "uuid": "^9.0.0" + }, + "peerDependencies": { + "@langchain/core": "*", + "langchain": "*", + "openai": "*" + }, + "peerDependenciesMeta": { + "@langchain/core": { + "optional": true + }, + "langchain": { + "optional": true + }, + "openai": { + "optional": true + } + } + }, + "node_modules/@langchain/community/node_modules/zod-to-json-schema": { + "version": "3.23.0", + "license": "ISC", + "peerDependencies": { + "zod": "^3.23.3" + } + }, + "node_modules/@langchain/core": { + "version": "0.1.63", + "license": "MIT", + "dependencies": { + "ansi-styles": "^5.0.0", + "camelcase": "6", + "decamelize": "1.2.0", + "js-tiktoken": "^1.0.12", + "langsmith": "~0.1.7", + "ml-distance": "^4.0.0", + "mustache": "^4.2.0", + "p-queue": "^6.6.2", + "p-retry": "4", + "uuid": "^9.0.0", + "zod": "^3.22.4", + "zod-to-json-schema": "^3.22.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@langchain/core/node_modules/langsmith": { + "version": "0.1.30", + "license": "MIT", + "dependencies": { + "@types/uuid": "^9.0.1", + "commander": "^10.0.1", + "p-queue": "^6.6.2", + "p-retry": "4", + "uuid": "^9.0.0" + }, + "peerDependencies": { + "@langchain/core": "*", + "langchain": "*", + "openai": "*" + }, + "peerDependenciesMeta": { + "@langchain/core": { + "optional": true + }, + "langchain": { + "optional": true + }, + "openai": { + "optional": true + } + } + }, + "node_modules/@langchain/core/node_modules/zod-to-json-schema": { + "version": "3.23.0", + "license": "ISC", + "peerDependencies": { + "zod": "^3.23.3" + } + }, + "node_modules/@langchain/openai": { + "version": "0.0.34", + "license": "MIT", + "dependencies": { + "@langchain/core": ">0.1.56 <0.3.0", + "js-tiktoken": "^1.0.12", + "openai": "^4.41.1", + "zod": "^3.22.4", + "zod-to-json-schema": "^3.22.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@langchain/openai/node_modules/openai": { + "version": "4.47.2", + "license": "Apache-2.0", + "dependencies": { + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7", + "web-streams-polyfill": "^3.2.1" + }, + "bin": { + "openai": "bin/cli" + } + }, + "node_modules/@langchain/openai/node_modules/openai/node_modules/@types/node": { + "version": "18.19.33", + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@langchain/openai/node_modules/zod-to-json-schema": { + "version": "3.23.0", + "license": "ISC", + "peerDependencies": { + "zod": "^3.23.3" + } + }, + "node_modules/@mixmark-io/domino": { + "version": "2.2.0", + "license": "BSD-2-Clause" + }, + "node_modules/@nextcloud/auth": { + "version": "2.4.0", + "license": "GPL-3.0-or-later", + "dependencies": { + "@nextcloud/browser-storage": "^0.4.0", + "@nextcloud/event-bus": "^3.3.1" + }, + "engines": { + "node": "^20.0.0", + "npm": "^10.0.0" + } + }, + "node_modules/@nextcloud/browser-storage": { + "version": "0.4.0", + "license": "GPL-3.0-or-later", + "dependencies": { + "core-js": "3.37.0" + }, + "engines": { + "node": "^20.0.0", + "npm": "^10.0.0" + } + }, + "node_modules/@nextcloud/capabilities": { + "version": "1.2.0", + "license": "GPL-3.0-or-later", + "dependencies": { + "@nextcloud/initial-state": "^2.1.0" + }, + "engines": { + "node": "^20.0.0", + "npm": "^10.0.0" + } + }, + "node_modules/@nextcloud/event-bus": { + "version": "3.3.1", + "license": "GPL-3.0-or-later", + "dependencies": { + "@types/node": "^20.12.12", + "semver": "^7.6.2" + }, + "engines": { + "node": "^20.0.0", + "npm": "^10.0.0" + } + }, + "node_modules/@nextcloud/files": { + "version": "3.9.0", + "license": "AGPL-3.0-or-later", + "dependencies": { + "@nextcloud/auth": "^2.4.0", + "@nextcloud/capabilities": "^1.2.0", + "@nextcloud/l10n": "^3.1.0", + "@nextcloud/logger": "^3.0.2", + "@nextcloud/paths": "^2.2.1", + "@nextcloud/router": "^3.0.1", + "@nextcloud/sharing": "^0.2.3", + "cancelable-promise": "^4.3.1", + "is-svg": "^5.1.0", + "typedoc-plugin-missing-exports": "^3.0.0", + "typescript-event-target": "^1.1.1", + "webdav": "^5.7.1" + }, + "engines": { + "node": "^20.0.0", + "npm": "^10.0.0" + } + }, + "node_modules/@nextcloud/initial-state": { + "version": "2.2.0", + "license": "GPL-3.0-or-later", + "engines": { + "node": "^20.0.0", + "npm": "^10.0.0" + } + }, + "node_modules/@nextcloud/l10n": { + "version": "3.1.0", + "license": "GPL-3.0-or-later", + "dependencies": { + "@nextcloud/router": "^3.0.1", + "@nextcloud/typings": "^1.8.0", + "@types/dompurify": "^3.0.5", + "@types/escape-html": "^1.0.4", + "dompurify": "^3.1.2", + "escape-html": "^1.0.3", + "node-gettext": "^3.0.0" + }, + "engines": { + "node": "^20.0.0", + "npm": "^10.0.0" + } + }, + "node_modules/@nextcloud/logger": { + "version": "3.0.2", + "license": "GPL-3.0-or-later", + "dependencies": { + "@nextcloud/auth": "^2.3.0" + }, + "engines": { + "node": "^20.0.0", + "npm": "^10.0.0" + } + }, + "node_modules/@nextcloud/paths": { + "version": "2.2.1", + "license": "GPL-3.0-or-later", + "engines": { + "node": "^20.0.0", + "npm": "^10.0.0" + } + }, + "node_modules/@nextcloud/router": { + "version": "3.0.1", + "license": "GPL-3.0-or-later", + "dependencies": { + "@nextcloud/typings": "^1.7.0" + }, + "engines": { + "node": "^20.0.0", + "npm": "^10.0.0" + } + }, + "node_modules/@nextcloud/sharing": { + "version": "0.2.3", + "license": "GPL-3.0-or-later", + "dependencies": { + "@nextcloud/initial-state": "^2.2.0" + }, + "engines": { + "node": "^20.0.0", + "npm": "^10.0.0" + } + }, + "node_modules/@nextcloud/typings": { + "version": "1.9.1", + "license": "GPL-3.0-or-later", + "dependencies": { + "@types/jquery": "3.5.16" + }, + "engines": { + "node": "^20.0.0", + "npm": "^10.0.0" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@one-ini/wasm": { + "version": "0.1.1", + "license": "MIT" + }, + "node_modules/@pedroslopez/moduleraid": { + "version": "5.0.2", + "license": "MIT" + }, + "node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/@puppeteer/browsers": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/@puppeteer/browsers/-/browsers-0.5.0.tgz", + "integrity": "sha512-Uw6oB7VvmPRLE4iKsjuOh8zgDabhNX67dzo8U/BB0f9527qx+4eeUs+korU98OhG5C4ubg7ufBgVi63XYwS6TQ==", + "license": "Apache-2.0", + "optional": true, + "peer": true, + "dependencies": { + "debug": "4.3.4", + "extract-zip": "2.0.1", + "https-proxy-agent": "5.0.1", + "progress": "2.0.3", + "proxy-from-env": "1.1.0", + "tar-fs": "2.1.1", + "unbzip2-stream": "1.4.3", + "yargs": "17.7.1" + }, + "bin": { + "browsers": "lib/cjs/main-cli.js" + }, + "engines": { + "node": ">=14.1.0" + }, + "peerDependencies": { + "typescript": ">= 4.7.4" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/@react-email/render": { + "version": "0.0.17", + "license": "MIT", + "dependencies": { + "html-to-text": "9.0.5", + "js-beautify": "^1.14.11", + "react-promise-suspense": "0.3.4" + }, + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "react": "^18.2.0", + "react-dom": "^18.2.0" + } + }, + "node_modules/@sapphire/async-queue": { + "version": "1.5.3", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@sapphire/shapeshift": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.3", + "lodash": "^4.17.21" + }, + "engines": { + "node": ">=v16" + } + }, + "node_modules/@sapphire/snowflake": { + "version": "3.5.3", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@selderee/plugin-htmlparser2": { + "version": "0.11.0", + "license": "MIT", + "dependencies": { + "domhandler": "^5.0.3", + "selderee": "^0.11.0" + }, + "funding": { + "url": "https://ko-fi.com/killymxi" + } + }, + "node_modules/@shikijs/core": { + "version": "1.13.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@types/hast": "^3.0.4" + } + }, + "node_modules/@sinclair/typebox": { + "version": "0.32.34", + "license": "MIT" + }, + "node_modules/@solyarisoftware/voskjs": { + "version": "1.2.8", + "license": "MIT", + "dependencies": { + "vosk": "^0.3.30", + "wav": "^1.0.2" + }, + "bin": { + "voskjs": "voskjs.js", + "voskjshttp": "examples/voskjshttp.js" + } + }, + "node_modules/@tootallnate/once": { + "version": "1.1.2", + "license": "MIT", + "engines": { + "node": ">= 6" + } + }, + "node_modules/@types/dompurify": { + "version": "3.0.5", + "license": "MIT", + "dependencies": { + "@types/trusted-types": "*" + } + }, + "node_modules/@types/escape-html": { + "version": "1.0.4", + "license": "MIT" + }, + "node_modules/@types/fluent-ffmpeg": { + "version": "2.1.26", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/fs-extra": { + "version": "11.0.4", + "license": "MIT", + "dependencies": { + "@types/jsonfile": "*", + "@types/node": "*" + } + }, + "node_modules/@types/fs-extra/node_modules/@types/node": { + "version": "20.10.5", + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/hast": { + "version": "3.0.4", + "license": "MIT", + "peer": true, + "dependencies": { + "@types/unist": "*" + } + }, + "node_modules/@types/jquery": { + "version": "3.5.16", + "license": "MIT", + "dependencies": { + "@types/sizzle": "*" + } + }, + "node_modules/@types/jsonfile": { + "version": "6.1.4", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/jsonfile/node_modules/@types/node": { + "version": "20.10.5", + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/minimist": { + "version": "1.2.5", + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "20.14.15", + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/node-cron": { + "version": "3.0.11", + "license": "MIT" + }, + "node_modules/@types/node-fetch": { + "version": "2.6.11", + "license": "MIT", + "dependencies": { + "@types/node": "*", + "form-data": "^4.0.0" + } + }, + "node_modules/@types/node-fetch/node_modules/@types/node": { + "version": "20.10.5", + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/ps-tree": { + "version": "1.1.6", + "license": "MIT" + }, + "node_modules/@types/retry": { + "version": "0.12.0", + "license": "MIT" + }, + "node_modules/@types/sizzle": { + "version": "2.3.8", + "license": "MIT" + }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "license": "MIT" + }, + "node_modules/@types/turndown": { + "version": "5.0.5", + "license": "MIT" + }, + "node_modules/@types/unist": { + "version": "3.0.3", + "license": "MIT", + "peer": true + }, + "node_modules/@types/uuid": { + "version": "9.0.8", + "license": "MIT" + }, + "node_modules/@types/which": { + "version": "3.0.4", + "license": "MIT" + }, + "node_modules/@types/ws": { + "version": "8.5.10", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/ws/node_modules/@types/node": { + "version": "20.10.5", + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/xml2js": { + "version": "0.4.14", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/xml2js/node_modules/@types/node": { + "version": "20.10.5", + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/@types/yauzl": { + "version": "2.10.3", + "resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz", + "integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==", + "license": "MIT", + "optional": true, + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@vladfrangu/async_event_emitter": { + "version": "2.4.6", + "license": "MIT", + "engines": { + "node": ">=v14.0.0", + "npm": ">=7.0.0" + } + }, + "node_modules/@zxing/text-encoding": { + "version": "0.9.0", + "license": "(Unlicense OR Apache-2.0)", + "optional": true + }, + "node_modules/abort-controller": { + "version": "3.0.0", + "license": "MIT", + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "engines": { + "node": ">=6.5" + } + }, + "node_modules/acorn": { + "version": "8.11.3", + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/agent-base": { + "version": "6.0.2", + "license": "MIT", + "dependencies": { + "debug": "4" + }, + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/agentkeepalive": { + "version": "4.5.0", + "license": "MIT", + "dependencies": { + "humanize-ms": "^1.2.1" + }, + "engines": { + "node": ">= 8.0.0" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "5.2.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/archiver": { + "version": "5.3.2", + "license": "MIT", + "optional": true, + "dependencies": { + "archiver-utils": "^2.1.0", + "async": "^3.2.4", + "buffer-crc32": "^0.2.1", + "readable-stream": "^3.6.0", + "readdir-glob": "^1.1.2", + "tar-stream": "^2.2.0", + "zip-stream": "^4.1.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/archiver-utils": { + "version": "2.1.0", + "license": "MIT", + "optional": true, + "dependencies": { + "glob": "^7.1.4", + "graceful-fs": "^4.2.0", + "lazystream": "^1.0.0", + "lodash.defaults": "^4.2.0", + "lodash.difference": "^4.5.0", + "lodash.flatten": "^4.4.0", + "lodash.isplainobject": "^4.0.6", + "lodash.union": "^4.6.0", + "normalize-path": "^3.0.0", + "readable-stream": "^2.0.0" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/archiver-utils/node_modules/glob": { + "version": "7.2.3", + "license": "ISC", + "optional": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/archiver-utils/node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "license": "ISC", + "optional": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/archiver-utils/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion": { + "version": "1.1.11", + "license": "MIT", + "optional": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/archiver-utils/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "optional": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/archiver-utils/node_modules/readable-stream/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "optional": true + }, + "node_modules/archiver-utils/node_modules/readable-stream/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/archiver/node_modules/async": { + "version": "3.2.5", + "license": "MIT", + "optional": true + }, + "node_modules/archiver/node_modules/buffer-crc32": { + "version": "0.2.13", + "license": "MIT", + "optional": true, + "engines": { + "node": "*" + } + }, + "node_modules/archiver/node_modules/readable-stream": { + "version": "3.6.2", + "license": "MIT", + "optional": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/archiver/node_modules/readable-stream/node_modules/string_decoder": { + "version": "1.3.0", + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/archiver/node_modules/readable-stream/node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/argparse": { + "version": "2.0.1", + "license": "Python-2.0" + }, + "node_modules/async": { + "version": "0.2.10" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "license": "MIT" + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/axios": { + "version": "1.7.7", + "license": "MIT", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/base-64": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/base64-js": { + "version": "1.5.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/big-integer": { + "version": "1.6.52", + "license": "Unlicense", + "optional": true, + "engines": { + "node": ">=0.6" + } + }, + "node_modules/binary": { + "version": "0.3.0", + "license": "MIT", + "optional": true, + "dependencies": { + "buffers": "~0.1.1", + "chainsaw": "~0.1.0" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/binary-search": { + "version": "1.3.6", + "license": "CC0-1.0" + }, + "node_modules/bl": { + "version": "4.1.0", + "license": "MIT", + "dependencies": { + "buffer": "^5.5.0", + "inherits": "^2.0.4", + "readable-stream": "^3.4.0" + } + }, + "node_modules/bl/node_modules/readable-stream": { + "version": "3.6.2", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/bl/node_modules/readable-stream/node_modules/string_decoder": { + "version": "1.3.0", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/bl/node_modules/readable-stream/node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/block-stream2": { + "version": "2.1.0", + "license": "MIT", + "dependencies": { + "readable-stream": "^3.4.0" + } + }, + "node_modules/block-stream2/node_modules/readable-stream": { + "version": "3.6.2", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/block-stream2/node_modules/readable-stream/node_modules/string_decoder": { + "version": "1.3.0", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/block-stream2/node_modules/readable-stream/node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/bluebird": { + "version": "3.4.7", + "license": "MIT", + "optional": true + }, + "node_modules/boolbase": { + "version": "1.0.0", + "license": "ISC" + }, + "node_modules/brace-expansion": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browser-or-node": { + "version": "2.1.1", + "license": "MIT" + }, + "node_modules/buffer": { + "version": "5.7.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "base64-js": "^1.3.1", + "ieee754": "^1.1.13" + } + }, + "node_modules/buffer-alloc": { + "version": "1.2.0", + "license": "MIT", + "dependencies": { + "buffer-alloc-unsafe": "^1.1.0", + "buffer-fill": "^1.0.0" + } + }, + "node_modules/buffer-alloc-unsafe": { + "version": "1.1.0", + "license": "MIT" + }, + "node_modules/buffer-crc32": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/buffer-fill": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "license": "MIT" + }, + "node_modules/buffer-indexof-polyfill": { + "version": "1.0.2", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/buffers": { + "version": "0.1.1", + "optional": true, + "engines": { + "node": ">=0.2.0" + } + }, + "node_modules/bun-types": { + "version": "1.1.29", + "resolved": "https://registry.npmjs.org/bun-types/-/bun-types-1.1.29.tgz", + "integrity": "sha512-En3/TzSPMPyl5UlUB1MHzHpcrZDakTm7mS203eLoX1fBoEa3PW+aSS8GAqVJ7Is/m34Z5ogL+ECniLY0uDaCPw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/node": "~20.12.8", + "@types/ws": "~8.5.10" + } + }, + "node_modules/bun-types/node_modules/@types/node": { + "version": "20.12.14", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/byte-length": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/call-bind": { + "version": "1.0.7", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/camelcase": { + "version": "6.3.0", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cancelable-promise": { + "version": "4.3.1", + "license": "MIT" + }, + "node_modules/chainsaw": { + "version": "0.1.0", + "license": "MIT/X11", + "optional": true, + "dependencies": { + "traverse": ">=0.3.0 <0.4" + } + }, + "node_modules/chalk": { + "version": "5.3.0", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/charenc": { + "version": "0.0.2", + "license": "BSD-3-Clause", + "engines": { + "node": "*" + } + }, + "node_modules/cheerio": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "cheerio-select": "^2.1.0", + "dom-serializer": "^2.0.0", + "domhandler": "^5.0.3", + "domutils": "^3.1.0", + "encoding-sniffer": "^0.2.0", + "htmlparser2": "^9.1.0", + "parse5": "^7.1.2", + "parse5-htmlparser2-tree-adapter": "^7.0.0", + "parse5-parser-stream": "^7.1.2", + "undici": "^6.19.5", + "whatwg-mimetype": "^4.0.0" + }, + "engines": { + "node": ">=18.17" + }, + "funding": { + "url": "https://github.com/cheeriojs/cheerio?sponsor=1" + } + }, + "node_modules/cheerio-select": { + "version": "2.1.0", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-select": "^5.1.0", + "css-what": "^6.1.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/chromium-bidi": { + "version": "0.4.7", + "resolved": "https://registry.npmjs.org/chromium-bidi/-/chromium-bidi-0.4.7.tgz", + "integrity": "sha512-6+mJuFXwTMU6I3vYLs6IL8A1DyQTPjCfIL971X0aMPVGRbGnNfl6i6Cl0NMbxi2bRYLGESt9T2ZIMRM5PAEcIQ==", + "license": "Apache-2.0", + "optional": true, + "peer": true, + "dependencies": { + "mitt": "3.0.0" + }, + "peerDependencies": { + "devtools-protocol": "*" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "license": "ISC", + "optional": true, + "peer": true, + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/cliui/node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "license": "MIT" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "license": "MIT", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/commander": { + "version": "10.0.1", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/complex.js": { + "version": "2.1.1", + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "patreon", + "url": "https://www.patreon.com/infusion" + } + }, + "node_modules/compress-commons": { + "version": "4.1.2", + "license": "MIT", + "optional": true, + "dependencies": { + "buffer-crc32": "^0.2.13", + "crc32-stream": "^4.0.2", + "normalize-path": "^3.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/compress-commons/node_modules/buffer-crc32": { + "version": "0.2.13", + "license": "MIT", + "optional": true, + "engines": { + "node": "*" + } + }, + "node_modules/compress-commons/node_modules/readable-stream": { + "version": "3.6.2", + "license": "MIT", + "optional": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/compress-commons/node_modules/readable-stream/node_modules/string_decoder": { + "version": "1.3.0", + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/compress-commons/node_modules/readable-stream/node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/concat-map": { + "version": "0.0.1", + "license": "MIT" + }, + "node_modules/config-chain": { + "version": "1.1.13", + "license": "MIT", + "dependencies": { + "ini": "^1.3.4", + "proto-list": "~1.2.1" + } + }, + "node_modules/config-chain/node_modules/ini": { + "version": "1.3.8", + "license": "ISC" + }, + "node_modules/cookie": { + "version": "0.6.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/core-js": { + "version": "3.37.0", + "hasInstallScript": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "license": "MIT" + }, + "node_modules/cosmiconfig": { + "version": "8.1.3", + "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-8.1.3.tgz", + "integrity": "sha512-/UkO2JKI18b5jVMJUp0lvKFMpa/Gye+ZgZjKD+DGEN9y7NRcf/nK1A0sp67ONmKtnDCNMS44E6jrk0Yc3bDuUw==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.0", + "parse-json": "^5.0.0", + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/d-fischer" + } + }, + "node_modules/crc-32": { + "version": "1.2.2", + "license": "Apache-2.0", + "optional": true, + "bin": { + "crc32": "bin/crc32.njs" + }, + "engines": { + "node": ">=0.8" + } + }, + "node_modules/crc32-stream": { + "version": "4.0.3", + "license": "MIT", + "optional": true, + "dependencies": { + "crc-32": "^1.2.0", + "readable-stream": "^3.4.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/crc32-stream/node_modules/readable-stream": { + "version": "3.6.2", + "license": "MIT", + "optional": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/crc32-stream/node_modules/readable-stream/node_modules/string_decoder": { + "version": "1.3.0", + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/crc32-stream/node_modules/readable-stream/node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/cross-fetch": { + "version": "3.1.8", + "license": "MIT", + "dependencies": { + "node-fetch": "^2.6.12" + } + }, + "node_modules/cross-spawn": { + "version": "7.0.3", + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/cross-spawn/node_modules/which": { + "version": "2.0.2", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/crypt": { + "version": "0.0.2", + "license": "BSD-3-Clause", + "engines": { + "node": "*" + } + }, + "node_modules/css-select": { + "version": "5.1.0", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0", + "css-what": "^6.1.0", + "domhandler": "^5.0.2", + "domutils": "^3.0.1", + "nth-check": "^2.0.1" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/css-what": { + "version": "6.1.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/sponsors/fb55" + } + }, + "node_modules/cssom": { + "version": "0.5.0", + "license": "MIT" + }, + "node_modules/data-uri-to-buffer": { + "version": "4.0.1", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/date-fns": { + "version": "3.6.0", + "license": "MIT", + "funding": { + "type": "github", + "url": "https://github.com/sponsors/kossnocorp" + } + }, + "node_modules/debug": { + "version": "4.3.4", + "license": "MIT", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/debug/node_modules/ms": { + "version": "2.1.2", + "license": "MIT" + }, + "node_modules/decamelize": { + "version": "1.2.0", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/decimal.js": { + "version": "10.4.3", + "license": "MIT" + }, + "node_modules/decode-uri-component": { + "version": "0.2.2", + "license": "MIT", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/deepmerge": { + "version": "4.3.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/devtools-protocol": { + "version": "0.0.1107588", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1107588.tgz", + "integrity": "sha512-yIR+pG9x65Xko7bErCUSQaDLrO/P1p3JUzEk7JCU4DowPcGHkTGUGQapcfcLc4qj0UaALwZ+cr0riFgiqpixcg==", + "license": "BSD-3-Clause", + "optional": true, + "peer": true + }, + "node_modules/digest-fetch": { + "version": "1.3.0", + "license": "ISC", + "dependencies": { + "base-64": "^0.1.0", + "md5": "^2.3.0" + } + }, + "node_modules/digest-fetch/node_modules/base-64": { + "version": "0.1.0" + }, + "node_modules/dir-glob": { + "version": "3.0.1", + "license": "MIT", + "dependencies": { + "path-type": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/discord-api-types": { + "version": "0.37.100", + "license": "MIT" + }, + "node_modules/discord.js": { + "version": "14.16.3", + "license": "Apache-2.0", + "dependencies": { + "@discordjs/builders": "^1.9.0", + "@discordjs/collection": "1.5.3", + "@discordjs/formatters": "^0.5.0", + "@discordjs/rest": "^2.4.0", + "@discordjs/util": "^1.1.1", + "@discordjs/ws": "1.1.1", + "@sapphire/snowflake": "3.5.3", + "discord-api-types": "0.37.100", + "fast-deep-equal": "3.1.3", + "lodash.snakecase": "4.1.1", + "tslib": "^2.6.3", + "undici": "6.19.8" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/discordjs/discord.js?sponsor" + } + }, + "node_modules/dom-serializer": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.2", + "entities": "^4.2.0" + }, + "funding": { + "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + } + }, + "node_modules/dom-serializer/node_modules/entities": { + "version": "4.5.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/domelementtype": { + "version": "2.3.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "BSD-2-Clause" + }, + "node_modules/domhandler": { + "version": "5.0.3", + "license": "BSD-2-Clause", + "dependencies": { + "domelementtype": "^2.3.0" + }, + "engines": { + "node": ">= 4" + }, + "funding": { + "url": "https://github.com/fb55/domhandler?sponsor=1" + } + }, + "node_modules/dompurify": { + "version": "3.1.6", + "license": "(MPL-2.0 OR Apache-2.0)" + }, + "node_modules/domutils": { + "version": "3.1.0", + "license": "BSD-2-Clause", + "dependencies": { + "dom-serializer": "^2.0.0", + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3" + }, + "funding": { + "url": "https://github.com/fb55/domutils?sponsor=1" + } + }, + "node_modules/dotenv": { + "version": "8.6.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=10" + } + }, + "node_modules/duplexer": { + "version": "0.1.2", + "license": "MIT" + }, + "node_modules/duplexer2": { + "version": "0.1.4", + "license": "BSD-3-Clause", + "optional": true, + "dependencies": { + "readable-stream": "^2.0.2" + } + }, + "node_modules/duplexer2/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "optional": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/duplexer2/node_modules/readable-stream/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "optional": true + }, + "node_modules/duplexer2/node_modules/readable-stream/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/eastasianwidth": { + "version": "0.2.0", + "license": "MIT" + }, + "node_modules/editorconfig": { + "version": "1.0.4", + "license": "MIT", + "dependencies": { + "@one-ini/wasm": "0.1.1", + "commander": "^10.0.0", + "minimatch": "9.0.1", + "semver": "^7.5.3" + }, + "bin": { + "editorconfig": "bin/editorconfig" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/editorconfig/node_modules/minimatch": { + "version": "9.0.1", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/elysia": { + "version": "1.1.17", + "license": "MIT", + "dependencies": { + "@sinclair/typebox": "0.32.34", + "cookie": "^0.6.0", + "fast-decode-uri-component": "^1.0.1", + "openapi-types": "^12.1.3" + }, + "peerDependencies": { + "@sinclair/typebox": ">= 0.32.0", + "openapi-types": ">= 12.0.0", + "typescript": ">= 5.0.0" + }, + "peerDependenciesMeta": { + "openapi-types": { + "optional": true + }, + "typescript": { + "optional": true + } + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "license": "MIT" + }, + "node_modules/encoding": { + "version": "0.1.13", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "iconv-lite": "^0.6.2" + } + }, + "node_modules/encoding-sniffer": { + "version": "0.2.0", + "license": "MIT", + "dependencies": { + "iconv-lite": "^0.6.3", + "whatwg-encoding": "^3.1.1" + }, + "funding": { + "url": "https://github.com/fb55/encoding-sniffer?sponsor=1" + } + }, + "node_modules/end-of-stream": { + "version": "1.4.4", + "license": "MIT", + "dependencies": { + "once": "^1.4.0" + } + }, + "node_modules/entities": { + "version": "5.0.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/error-ex": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz", + "integrity": "sha512-7dFHNmqeFSEt2ZBsCriorKnn3Z2pj+fd9kmI6QoWw4//DL+icEBfc0U7qJCisqrTsKTjw4fNFy2pW9OqStD84g==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "is-arrayish": "^0.2.1" + } + }, + "node_modules/es-define-property": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.4" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "license": "MIT" + }, + "node_modules/escape-latex": { + "version": "1.2.0", + "license": "MIT" + }, + "node_modules/escape-string-regexp": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", + "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/event-stream": { + "version": "3.3.4", + "license": "MIT", + "dependencies": { + "duplexer": "~0.1.1", + "from": "~0", + "map-stream": "~0.1.0", + "pause-stream": "0.0.11", + "split": "0.3", + "stream-combiner": "~0.0.4", + "through": "~2.3.1" + } + }, + "node_modules/event-target-shim": { + "version": "5.0.1", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/eventemitter3": { + "version": "5.0.1", + "license": "MIT" + }, + "node_modules/expr-eval": { + "version": "2.0.2", + "license": "MIT" + }, + "node_modules/extract-zip": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz", + "integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==", + "license": "BSD-2-Clause", + "dependencies": { + "debug": "^4.1.1", + "get-stream": "^5.1.0", + "yauzl": "^2.10.0" + }, + "bin": { + "extract-zip": "cli.js" + }, + "engines": { + "node": ">= 10.17.0" + }, + "optionalDependencies": { + "@types/yauzl": "^2.9.1" + } + }, + "node_modules/fast-decode-uri-component": { + "version": "1.0.1", + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "license": "MIT" + }, + "node_modules/fast-glob": { + "version": "3.3.2", + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-xml-parser": { + "version": "4.4.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/NaturalIntelligence" + }, + { + "type": "paypal", + "url": "https://paypal.me/naturalintelligence" + } + ], + "license": "MIT", + "dependencies": { + "strnum": "^1.0.5" + }, + "bin": { + "fxparser": "src/cli/cli.js" + } + }, + "node_modules/fastq": { + "version": "1.17.1", + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/fd-slicer": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz", + "integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==", + "license": "MIT", + "dependencies": { + "pend": "~1.2.0" + } + }, + "node_modules/fetch-blob": { + "version": "3.2.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "paypal", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "dependencies": { + "node-domexception": "^1.0.0", + "web-streams-polyfill": "^3.0.3" + }, + "engines": { + "node": "^12.20 || >= 14.13" + } + }, + "node_modules/ffi-napi": { + "version": "4.0.3", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "debug": "^4.1.1", + "get-uv-event-loop-napi-h": "^1.0.5", + "node-addon-api": "^3.0.0", + "node-gyp-build": "^4.2.1", + "ref-napi": "^2.0.1 || ^3.0.2", + "ref-struct-di": "^1.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/filter-obj": { + "version": "1.1.0", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/flat": { + "version": "5.0.2", + "license": "BSD-3-Clause", + "bin": { + "flat": "cli.js" + } + }, + "node_modules/fluent-ffmpeg": { + "version": "2.1.3", + "license": "MIT", + "dependencies": { + "async": "^0.2.9", + "which": "^1.1.1" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/follow-redirects": { + "version": "1.15.6", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "license": "MIT", + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/for-each": { + "version": "0.3.3", + "license": "MIT", + "dependencies": { + "is-callable": "^1.1.3" + } + }, + "node_modules/foreground-child": { + "version": "3.1.1", + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/form-data": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/form-data-encoder": { + "version": "1.7.2", + "license": "MIT" + }, + "node_modules/formdata-node": { + "version": "4.4.1", + "license": "MIT", + "dependencies": { + "node-domexception": "1.0.0", + "web-streams-polyfill": "4.0.0-beta.3" + }, + "engines": { + "node": ">= 12.20" + } + }, + "node_modules/formdata-node/node_modules/web-streams-polyfill": { + "version": "4.0.0-beta.3", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, + "node_modules/formdata-polyfill": { + "version": "4.0.10", + "license": "MIT", + "dependencies": { + "fetch-blob": "^3.1.2" + }, + "engines": { + "node": ">=12.20.0" + } + }, + "node_modules/fraction.js": { + "version": "4.3.4", + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "patreon", + "url": "https://github.com/sponsors/rawify" + } + }, + "node_modules/from": { + "version": "0.1.7", + "license": "MIT" + }, + "node_modules/fs-constants": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/fs-extra": { + "version": "10.1.0", + "license": "MIT", + "optional": true, + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "license": "ISC" + }, + "node_modules/fstream": { + "version": "1.0.12", + "license": "ISC", + "optional": true, + "dependencies": { + "graceful-fs": "^4.1.2", + "inherits": "~2.0.0", + "mkdirp": ">=0.5 0", + "rimraf": "2" + }, + "engines": { + "node": ">=0.6" + } + }, + "node_modules/fstream/node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "license": "MIT", + "optional": true, + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "mkdirp": "bin/cmd.js" + } + }, + "node_modules/fstream/node_modules/rimraf": { + "version": "2.7.1", + "license": "ISC", + "optional": true, + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + } + }, + "node_modules/fstream/node_modules/rimraf/node_modules/glob": { + "version": "7.2.3", + "license": "ISC", + "optional": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/fstream/node_modules/rimraf/node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "license": "ISC", + "optional": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/fstream/node_modules/rimraf/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion": { + "version": "1.1.11", + "license": "MIT", + "optional": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/fuse.js": { + "version": "7.0.0", + "license": "Apache-2.0", + "engines": { + "node": ">=10" + } + }, + "node_modules/fuzzysort": { + "version": "3.0.2", + "license": "MIT" + }, + "node_modules/fx": { + "version": "35.0.0", + "license": "MIT", + "bin": { + "fx": "index.js" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "license": "ISC", + "optional": true, + "peer": true, + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-intrinsic": { + "version": "1.2.4", + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "has-proto": "^1.0.1", + "has-symbols": "^1.0.3", + "hasown": "^2.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-stream": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz", + "integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==", + "license": "MIT", + "dependencies": { + "pump": "^3.0.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-symbol-from-current-process-h": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/get-uv-event-loop-napi-h": { + "version": "1.0.6", + "license": "MIT", + "dependencies": { + "get-symbol-from-current-process-h": "^1.0.1" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/globby": { + "version": "13.2.2", + "license": "MIT", + "dependencies": { + "dir-glob": "^3.0.1", + "fast-glob": "^3.3.0", + "ignore": "^5.2.4", + "merge2": "^1.4.1", + "slash": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/gopd": { + "version": "1.0.1", + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.1.3" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "license": "ISC" + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.0.3", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.0.3", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hot-patcher": { + "version": "2.0.1", + "license": "MIT" + }, + "node_modules/html-escaper": { + "version": "3.0.3", + "license": "MIT" + }, + "node_modules/html-to-text": { + "version": "9.0.5", + "license": "MIT", + "dependencies": { + "@selderee/plugin-htmlparser2": "^0.11.0", + "deepmerge": "^4.3.1", + "dom-serializer": "^2.0.0", + "htmlparser2": "^8.0.2", + "selderee": "^0.11.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/html-to-text/node_modules/htmlparser2": { + "version": "8.0.2", + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1", + "entities": "^4.4.0" + } + }, + "node_modules/html-to-text/node_modules/htmlparser2/node_modules/entities": { + "version": "4.5.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/htmlparser2": { + "version": "9.1.0", + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.1.0", + "entities": "^4.5.0" + } + }, + "node_modules/htmlparser2/node_modules/entities": { + "version": "4.5.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/http-proxy-agent": { + "version": "4.0.1", + "license": "MIT", + "dependencies": { + "@tootallnate/once": "1", + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/https-proxy-agent": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", + "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", + "license": "MIT", + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/humanize-ms": { + "version": "1.2.1", + "license": "MIT", + "dependencies": { + "ms": "^2.0.0" + } + }, + "node_modules/i": { + "version": "0.3.7", + "engines": { + "node": ">=0.4" + } + }, + "node_modules/iconv-lite": { + "version": "0.6.3", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ieee754": { + "version": "1.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "BSD-3-Clause" + }, + "node_modules/ignore": { + "version": "5.3.1", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.0.tgz", + "integrity": "sha512-veYYhQa+D1QBKznvhUHxb8faxlrwUnxseDAbAp457E0wLNio2bOSKnjYDhMj+YiAq61xrMGhQk9iXVk5FzgQMw==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "license": "ISC", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "license": "ISC" + }, + "node_modules/interpret": { + "version": "1.4.0", + "license": "MIT", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/ipaddr.js": { + "version": "2.2.0", + "license": "MIT", + "engines": { + "node": ">= 10" + } + }, + "node_modules/is-any-array": { + "version": "2.0.1", + "license": "MIT" + }, + "node_modules/is-arguments": { + "version": "1.1.1", + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.2", + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-arrayish": { + "version": "0.2.1", + "resolved": "https://registry.npmjs.org/is-arrayish/-/is-arrayish-0.2.1.tgz", + "integrity": "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg==", + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/is-buffer": { + "version": "1.1.6", + "license": "MIT" + }, + "node_modules/is-callable": { + "version": "1.2.7", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.13.1", + "license": "MIT", + "dependencies": { + "hasown": "^2.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-generator-function": { + "version": "1.0.10", + "license": "MIT", + "dependencies": { + "has-tostringtag": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-svg": { + "version": "5.1.0", + "license": "MIT", + "dependencies": { + "fast-xml-parser": "^4.4.1" + }, + "engines": { + "node": ">=14.16" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.13", + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "0.0.1", + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "license": "ISC" + }, + "node_modules/isomorphic-unfetch": { + "version": "3.1.0", + "license": "MIT", + "dependencies": { + "node-fetch": "^2.6.1", + "unfetch": "^4.2.0" + } + }, + "node_modules/jackspeak": { + "version": "3.1.2", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/javascript-natural-sort": { + "version": "0.7.1", + "license": "MIT" + }, + "node_modules/javascript-stringify": { + "version": "2.1.0", + "license": "MIT" + }, + "node_modules/jintr": { + "version": "1.1.0", + "funding": [ + "https://github.com/sponsors/LuanRT" + ], + "license": "MIT", + "dependencies": { + "acorn": "^8.8.0" + } + }, + "node_modules/js-beautify": { + "version": "1.15.1", + "license": "MIT", + "dependencies": { + "config-chain": "^1.1.13", + "editorconfig": "^1.0.4", + "glob": "^10.3.3", + "js-cookie": "^3.0.5", + "nopt": "^7.2.0" + }, + "bin": { + "css-beautify": "js/bin/css-beautify.js", + "html-beautify": "js/bin/html-beautify.js", + "js-beautify": "js/bin/js-beautify.js" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/js-beautify/node_modules/glob": { + "version": "10.4.1", + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/js-beautify/node_modules/glob/node_modules/minimatch": { + "version": "9.0.4", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/js-beautify/node_modules/nopt": { + "version": "7.2.1", + "license": "ISC", + "dependencies": { + "abbrev": "^2.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/js-beautify/node_modules/nopt/node_modules/abbrev": { + "version": "2.0.0", + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/js-cookie": { + "version": "3.0.5", + "license": "MIT", + "engines": { + "node": ">=14" + } + }, + "node_modules/js-tiktoken": { + "version": "1.0.12", + "license": "MIT", + "dependencies": { + "base64-js": "^1.5.1" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsonfile": { + "version": "6.1.0", + "license": "MIT", + "dependencies": { + "universalify": "^2.0.0" + }, + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/jsonpointer": { + "version": "5.0.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/langchain": { + "version": "0.0.212", + "license": "MIT", + "dependencies": { + "@anthropic-ai/sdk": "^0.9.1", + "@langchain/community": "~0.0.8", + "@langchain/core": "~0.1.3", + "@langchain/openai": "~0.0.7", + "binary-extensions": "^2.2.0", + "expr-eval": "^2.0.2", + "js-tiktoken": "^1.0.7", + "js-yaml": "^4.1.0", + "jsonpointer": "^5.0.1", + "langchainhub": "~0.0.6", + "langsmith": "~0.0.48", + "ml-distance": "^4.0.0", + "openapi-types": "^12.1.3", + "p-retry": "4", + "uuid": "^9.0.0", + "yaml": "^2.2.1", + "zod": "^3.22.3", + "zod-to-json-schema": "3.20.3" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@aws-sdk/client-s3": "^3.310.0", + "@aws-sdk/client-sagemaker-runtime": "^3.310.0", + "@aws-sdk/client-sfn": "^3.310.0", + "@aws-sdk/credential-provider-node": "^3.388.0", + "@azure/storage-blob": "^12.15.0", + "@gomomento/sdk": "^1.51.1", + "@gomomento/sdk-core": "^1.51.1", + "@gomomento/sdk-web": "^1.51.1", + "@google-ai/generativelanguage": "^0.2.1", + "@google-cloud/storage": "^6.10.1", + "@notionhq/client": "^2.2.10", + "@pinecone-database/pinecone": "^1.1.0", + "@supabase/supabase-js": "^2.10.0", + "@vercel/kv": "^0.2.3", + "@xata.io/client": "^0.28.0", + "apify-client": "^2.7.1", + "assemblyai": "^4.0.0", + "axios": "*", + "cheerio": "^1.0.0-rc.12", + "chromadb": "*", + "convex": "^1.3.1", + "d3-dsv": "^2.0.0", + "epub2": "^3.0.1", + "fast-xml-parser": "^4.2.7", + "google-auth-library": "^8.9.0", + "googleapis": "^126.0.1", + "html-to-text": "^9.0.5", + "ignore": "^5.2.0", + "ioredis": "^5.3.2", + "jsdom": "*", + "mammoth": "^1.6.0", + "mongodb": "^5.2.0", + "node-llama-cpp": "*", + "notion-to-md": "^3.1.0", + "officeparser": "^4.0.4", + "pdf-parse": "1.1.1", + "peggy": "^3.0.2", + "playwright": "^1.32.1", + "puppeteer": "^19.7.2", + "pyodide": "^0.24.1", + "redis": "^4.6.4", + "sonix-speech-recognition": "^2.1.1", + "srt-parser-2": "^1.2.2", + "typeorm": "^0.3.12", + "vectordb": "^0.1.4", + "weaviate-ts-client": "^1.4.0", + "web-auth-library": "^1.0.3", + "ws": "^8.14.2", + "youtube-transcript": "^1.0.6", + "youtubei.js": "^5.8.0" + }, + "peerDependenciesMeta": { + "@aws-sdk/client-s3": { + "optional": true + }, + "@aws-sdk/client-sagemaker-runtime": { + "optional": true + }, + "@aws-sdk/client-sfn": { + "optional": true + }, + "@aws-sdk/credential-provider-node": { + "optional": true + }, + "@azure/storage-blob": { + "optional": true + }, + "@gomomento/sdk": { + "optional": true + }, + "@gomomento/sdk-core": { + "optional": true + }, + "@gomomento/sdk-web": { + "optional": true + }, + "@google-ai/generativelanguage": { + "optional": true + }, + "@google-cloud/storage": { + "optional": true + }, + "@notionhq/client": { + "optional": true + }, + "@pinecone-database/pinecone": { + "optional": true + }, + "@supabase/supabase-js": { + "optional": true + }, + "@vercel/kv": { + "optional": true + }, + "@xata.io/client": { + "optional": true + }, + "apify-client": { + "optional": true + }, + "assemblyai": { + "optional": true + }, + "axios": { + "optional": true + }, + "cheerio": { + "optional": true + }, + "chromadb": { + "optional": true + }, + "convex": { + "optional": true + }, + "d3-dsv": { + "optional": true + }, + "epub2": { + "optional": true + }, + "faiss-node": { + "optional": true + }, + "fast-xml-parser": { + "optional": true + }, + "google-auth-library": { + "optional": true + }, + "googleapis": { + "optional": true + }, + "html-to-text": { + "optional": true + }, + "ignore": { + "optional": true + }, + "ioredis": { + "optional": true + }, + "jsdom": { + "optional": true + }, + "mammoth": { + "optional": true + }, + "mongodb": { + "optional": true + }, + "node-llama-cpp": { + "optional": true + }, + "notion-to-md": { + "optional": true + }, + "officeparser": { + "optional": true + }, + "pdf-parse": { + "optional": true + }, + "peggy": { + "optional": true + }, + "playwright": { + "optional": true + }, + "puppeteer": { + "optional": true + }, + "pyodide": { + "optional": true + }, + "redis": { + "optional": true + }, + "sonix-speech-recognition": { + "optional": true + }, + "srt-parser-2": { + "optional": true + }, + "typeorm": { + "optional": true + }, + "vectordb": { + "optional": true + }, + "weaviate-ts-client": { + "optional": true + }, + "web-auth-library": { + "optional": true + }, + "ws": { + "optional": true + }, + "youtube-transcript": { + "optional": true + }, + "youtubei.js": { + "optional": true + } + } + }, + "node_modules/langchain/node_modules/zod-to-json-schema": { + "version": "3.20.3", + "license": "ISC", + "peerDependencies": { + "zod": "^3.20.0" + } + }, + "node_modules/langchainhub": { + "version": "0.0.11", + "license": "MIT" + }, + "node_modules/langsmith": { + "version": "0.0.70", + "license": "MIT", + "dependencies": { + "@types/uuid": "^9.0.1", + "commander": "^10.0.1", + "p-queue": "^6.6.2", + "p-retry": "4", + "uuid": "^9.0.0" + }, + "bin": { + "langsmith": "dist/cli/main.cjs" + } + }, + "node_modules/layerr": { + "version": "3.0.0", + "license": "MIT" + }, + "node_modules/lazystream": { + "version": "1.0.1", + "license": "MIT", + "optional": true, + "dependencies": { + "readable-stream": "^2.0.5" + }, + "engines": { + "node": ">= 0.6.3" + } + }, + "node_modules/lazystream/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "optional": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/lazystream/node_modules/readable-stream/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "optional": true + }, + "node_modules/lazystream/node_modules/readable-stream/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/leac": { + "version": "0.6.0", + "license": "MIT", + "funding": { + "url": "https://ko-fi.com/killymxi" + } + }, + "node_modules/lines-and-columns": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz", + "integrity": "sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==", + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/linkedom": { + "version": "0.14.26", + "license": "ISC", + "dependencies": { + "css-select": "^5.1.0", + "cssom": "^0.5.0", + "html-escaper": "^3.0.3", + "htmlparser2": "^8.0.1", + "uhyphen": "^0.2.0" + } + }, + "node_modules/linkedom/node_modules/htmlparser2": { + "version": "8.0.2", + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1", + "entities": "^4.4.0" + } + }, + "node_modules/linkedom/node_modules/htmlparser2/node_modules/entities": { + "version": "4.5.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/linkify-it": { + "version": "5.0.0", + "license": "MIT", + "peer": true, + "dependencies": { + "uc.micro": "^2.0.0" + } + }, + "node_modules/listenercount": { + "version": "1.0.1", + "license": "ISC", + "optional": true + }, + "node_modules/lodash": { + "version": "4.17.21", + "license": "MIT" + }, + "node_modules/lodash.defaults": { + "version": "4.2.0", + "license": "MIT", + "optional": true + }, + "node_modules/lodash.difference": { + "version": "4.5.0", + "license": "MIT", + "optional": true + }, + "node_modules/lodash.flatten": { + "version": "4.4.0", + "license": "MIT", + "optional": true + }, + "node_modules/lodash.get": { + "version": "4.4.2", + "license": "MIT" + }, + "node_modules/lodash.isplainobject": { + "version": "4.0.6", + "license": "MIT", + "optional": true + }, + "node_modules/lodash.snakecase": { + "version": "4.1.1", + "license": "MIT" + }, + "node_modules/lodash.union": { + "version": "4.6.0", + "license": "MIT", + "optional": true + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "license": "MIT", + "peer": true, + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "10.2.2", + "license": "ISC", + "engines": { + "node": "14 || >=16.14" + } + }, + "node_modules/lunr": { + "version": "2.3.9", + "license": "MIT", + "peer": true + }, + "node_modules/m3u8stream": { + "version": "0.8.6", + "license": "MIT", + "dependencies": { + "miniget": "^4.2.2", + "sax": "^1.2.4" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/magic-bytes.js": { + "version": "1.10.0", + "license": "MIT" + }, + "node_modules/map-stream": { + "version": "0.1.0" + }, + "node_modules/markdown-it": { + "version": "14.1.0", + "license": "MIT", + "peer": true, + "dependencies": { + "argparse": "^2.0.1", + "entities": "^4.4.0", + "linkify-it": "^5.0.0", + "mdurl": "^2.0.0", + "punycode.js": "^2.3.1", + "uc.micro": "^2.1.0" + }, + "bin": { + "markdown-it": "bin/markdown-it.mjs" + } + }, + "node_modules/markdown-it/node_modules/entities": { + "version": "4.5.0", + "license": "BSD-2-Clause", + "peer": true, + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/mathjs": { + "version": "12.4.3", + "license": "Apache-2.0", + "dependencies": { + "@babel/runtime": "^7.24.4", + "complex.js": "^2.1.1", + "decimal.js": "^10.4.3", + "escape-latex": "^1.2.0", + "fraction.js": "4.3.4", + "javascript-natural-sort": "^0.7.1", + "seedrandom": "^3.0.5", + "tiny-emitter": "^2.1.0", + "typed-function": "^4.1.1" + }, + "bin": { + "mathjs": "bin/cli.js" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/md5": { + "version": "2.3.0", + "license": "BSD-3-Clause", + "dependencies": { + "charenc": "0.0.2", + "crypt": "0.0.2", + "is-buffer": "~1.1.6" + } + }, + "node_modules/mdurl": { + "version": "2.0.0", + "license": "MIT", + "peer": true + }, + "node_modules/merge2": { + "version": "1.4.1", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/meta-fetcher": { + "version": "3.1.1", + "license": "MIT", + "dependencies": { + "cheerio": "^1.0.0-rc.6", + "isomorphic-unfetch": "^3.1.0" + }, + "funding": { + "url": "https://www.buymeacoffee.com/rocktimcodes" + } + }, + "node_modules/meta-fetcher/node_modules/cheerio": { + "version": "1.0.0-rc.12", + "license": "MIT", + "dependencies": { + "cheerio-select": "^2.1.0", + "dom-serializer": "^2.0.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1", + "htmlparser2": "^8.0.1", + "parse5": "^7.0.0", + "parse5-htmlparser2-tree-adapter": "^7.0.0" + }, + "engines": { + "node": ">= 6" + }, + "funding": { + "url": "https://github.com/cheeriojs/cheerio?sponsor=1" + } + }, + "node_modules/meta-fetcher/node_modules/cheerio/node_modules/htmlparser2": { + "version": "8.0.2", + "funding": [ + "https://github.com/fb55/htmlparser2?sponsor=1", + { + "type": "github", + "url": "https://github.com/sponsors/fb55" + } + ], + "license": "MIT", + "dependencies": { + "domelementtype": "^2.3.0", + "domhandler": "^5.0.3", + "domutils": "^3.0.1", + "entities": "^4.4.0" + } + }, + "node_modules/meta-fetcher/node_modules/cheerio/node_modules/htmlparser2/node_modules/entities": { + "version": "4.5.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/mic": { + "version": "2.1.2", + "license": "MIT" + }, + "node_modules/micromatch": { + "version": "4.0.8", + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/mime": { + "version": "3.0.0", + "license": "MIT", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "license": "MIT", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/miniget": { + "version": "4.2.3", + "license": "MIT", + "engines": { + "node": ">=12" + } + }, + "node_modules/minimatch": { + "version": "9.0.5", + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minio": { + "version": "8.0.1", + "license": "Apache-2.0", + "dependencies": { + "async": "^3.2.4", + "block-stream2": "^2.1.0", + "browser-or-node": "^2.1.1", + "buffer-crc32": "^1.0.0", + "eventemitter3": "^5.0.1", + "fast-xml-parser": "^4.2.2", + "ipaddr.js": "^2.0.1", + "lodash": "^4.17.21", + "mime-types": "^2.1.35", + "query-string": "^7.1.3", + "stream-json": "^1.8.0", + "through2": "^4.0.2", + "web-encoding": "^1.1.5", + "xml2js": "^0.5.0" + }, + "engines": { + "node": "^16 || ^18 || >=20" + } + }, + "node_modules/minio/node_modules/async": { + "version": "3.2.5", + "license": "MIT" + }, + "node_modules/minio/node_modules/xml2js": { + "version": "0.5.0", + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/minipass": { + "version": "7.1.2", + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/mitt": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mitt/-/mitt-3.0.0.tgz", + "integrity": "sha512-7dX2/10ITVyqh4aOSVI9gdape+t9l2/8QxHrFmUXu4EEUpdlxl6RudZUPZoc+zuY2hk1j7XxVroIVIan/pD/SQ==", + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/mkdirp-classic": { + "version": "0.5.3", + "resolved": "https://registry.npmjs.org/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz", + "integrity": "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==", + "license": "MIT" + }, + "node_modules/ml-array-mean": { + "version": "1.1.6", + "license": "MIT", + "dependencies": { + "ml-array-sum": "^1.1.6" + } + }, + "node_modules/ml-array-sum": { + "version": "1.1.6", + "license": "MIT", + "dependencies": { + "is-any-array": "^2.0.0" + } + }, + "node_modules/ml-distance": { + "version": "4.0.1", + "license": "MIT", + "dependencies": { + "ml-array-mean": "^1.1.6", + "ml-distance-euclidean": "^2.0.0", + "ml-tree-similarity": "^1.0.0" + } + }, + "node_modules/ml-distance-euclidean": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/ml-tree-similarity": { + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "binary-search": "^1.3.5", + "num-sort": "^2.0.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "license": "MIT" + }, + "node_modules/mustache": { + "version": "4.2.0", + "license": "MIT", + "bin": { + "mustache": "bin/mustache" + } + }, + "node_modules/nanoid": { + "version": "5.0.7", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.js" + }, + "engines": { + "node": "^18 || >=20" + } + }, + "node_modules/nested-property": { + "version": "4.0.0", + "license": "MIT" + }, + "node_modules/nextcloud-node-client": { + "version": "1.8.1", + "license": "Apache-2.0", + "dependencies": { + "debug": "^4.1.0", + "dotenv": "^8.2.0", + "fast-xml-parser": "^3.16.0", + "http-proxy-agent": "^4.0.1", + "node-fetch": "^2.6.0", + "tslog": "^2.6.2", + "vcap_services": "^0.7.1" + } + }, + "node_modules/nextcloud-node-client/node_modules/fast-xml-parser": { + "version": "3.21.1", + "license": "MIT", + "dependencies": { + "strnum": "^1.0.4" + }, + "bin": { + "xml2js": "cli.js" + }, + "funding": { + "type": "paypal", + "url": "https://paypal.me/naturalintelligence" + } + }, + "node_modules/node-addon-api": { + "version": "3.2.1", + "license": "MIT" + }, + "node_modules/node-cron": { + "version": "3.0.3", + "license": "ISC", + "dependencies": { + "uuid": "8.3.2" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/node-cron/node_modules/uuid": { + "version": "8.3.2", + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/node-domexception": { + "version": "1.0.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/jimmywarting" + }, + { + "type": "github", + "url": "https://paypal.me/jimmywarting" + } + ], + "license": "MIT", + "engines": { + "node": ">=10.5.0" + } + }, + "node_modules/node-fetch": { + "version": "2.7.0", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/node-gettext": { + "version": "3.0.0", + "dependencies": { + "lodash.get": "^4.4.2" + } + }, + "node_modules/node-gyp-build": { + "version": "4.8.1", + "license": "MIT", + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/node-webpmux": { + "version": "3.1.7", + "license": "ISC" + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm": { + "version": "10.9.0", + "bundleDependencies": [ + "@isaacs/string-locale-compare", + "@npmcli/arborist", + "@npmcli/config", + "@npmcli/fs", + "@npmcli/map-workspaces", + "@npmcli/package-json", + "@npmcli/promise-spawn", + "@npmcli/redact", + "@npmcli/run-script", + "@sigstore/tuf", + "abbrev", + "archy", + "cacache", + "chalk", + "ci-info", + "cli-columns", + "fastest-levenshtein", + "fs-minipass", + "glob", + "graceful-fs", + "hosted-git-info", + "ini", + "init-package-json", + "is-cidr", + "json-parse-even-better-errors", + "libnpmaccess", + "libnpmdiff", + "libnpmexec", + "libnpmfund", + "libnpmhook", + "libnpmorg", + "libnpmpack", + "libnpmpublish", + "libnpmsearch", + "libnpmteam", + "libnpmversion", + "make-fetch-happen", + "minimatch", + "minipass", + "minipass-pipeline", + "ms", + "node-gyp", + "nopt", + "normalize-package-data", + "npm-audit-report", + "npm-install-checks", + "npm-package-arg", + "npm-pick-manifest", + "npm-profile", + "npm-registry-fetch", + "npm-user-validate", + "p-map", + "pacote", + "parse-conflict-json", + "proc-log", + "qrcode-terminal", + "read", + "semver", + "spdx-expression-parse", + "ssri", + "supports-color", + "tar", + "text-table", + "tiny-relative-date", + "treeverse", + "validate-npm-package-name", + "which", + "write-file-atomic" + ], + "license": "Artistic-2.0", + "workspaces": [ + "docs", + "smoke-tests", + "mock-globals", + "mock-registry", + "workspaces/*" + ], + "dependencies": { + "@isaacs/string-locale-compare": "^1.1.0", + "@npmcli/arborist": "^8.0.0", + "@npmcli/config": "^9.0.0", + "@npmcli/fs": "^4.0.0", + "@npmcli/map-workspaces": "^4.0.1", + "@npmcli/package-json": "^6.0.1", + "@npmcli/promise-spawn": "^8.0.1", + "@npmcli/redact": "^3.0.0", + "@npmcli/run-script": "^9.0.1", + "@sigstore/tuf": "^2.3.4", + "abbrev": "^3.0.0", + "archy": "~1.0.0", + "cacache": "^19.0.1", + "chalk": "^5.3.0", + "ci-info": "^4.0.0", + "cli-columns": "^4.0.0", + "fastest-levenshtein": "^1.0.16", + "fs-minipass": "^3.0.3", + "glob": "^10.4.5", + "graceful-fs": "^4.2.11", + "hosted-git-info": "^8.0.0", + "ini": "^5.0.0", + "init-package-json": "^7.0.1", + "is-cidr": "^5.1.0", + "json-parse-even-better-errors": "^4.0.0", + "libnpmaccess": "^9.0.0", + "libnpmdiff": "^7.0.0", + "libnpmexec": "^9.0.0", + "libnpmfund": "^6.0.0", + "libnpmhook": "^11.0.0", + "libnpmorg": "^7.0.0", + "libnpmpack": "^8.0.0", + "libnpmpublish": "^10.0.0", + "libnpmsearch": "^8.0.0", + "libnpmteam": "^7.0.0", + "libnpmversion": "^7.0.0", + "make-fetch-happen": "^14.0.1", + "minimatch": "^9.0.5", + "minipass": "^7.1.1", + "minipass-pipeline": "^1.2.4", + "ms": "^2.1.2", + "node-gyp": "^10.2.0", + "nopt": "^8.0.0", + "normalize-package-data": "^7.0.0", + "npm-audit-report": "^6.0.0", + "npm-install-checks": "^7.1.0", + "npm-package-arg": "^12.0.0", + "npm-pick-manifest": "^10.0.0", + "npm-profile": "^11.0.1", + "npm-registry-fetch": "^18.0.1", + "npm-user-validate": "^3.0.0", + "p-map": "^4.0.0", + "pacote": "^19.0.0", + "parse-conflict-json": "^4.0.0", + "proc-log": "^5.0.0", + "qrcode-terminal": "^0.12.0", + "read": "^4.0.0", + "semver": "^7.6.3", + "spdx-expression-parse": "^4.0.0", + "ssri": "^12.0.0", + "supports-color": "^9.4.0", + "tar": "^6.2.1", + "text-table": "~0.2.0", + "tiny-relative-date": "^1.3.0", + "treeverse": "^3.0.0", + "validate-npm-package-name": "^6.0.0", + "which": "^5.0.0", + "write-file-atomic": "^6.0.0" + }, + "bin": { + "npm": "bin/npm-cli.js", + "npx": "bin/npx-cli.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@isaacs/cliui": { + "version": "8.0.2", + "inBundle": true, + "license": "ISC", + "dependencies": { + "string-width": "^5.1.2", + "string-width-cjs": "npm:string-width@^4.2.0", + "strip-ansi": "^7.0.1", + "strip-ansi-cjs": "npm:strip-ansi@^6.0.1", + "wrap-ansi": "^8.1.0", + "wrap-ansi-cjs": "npm:wrap-ansi@^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/npm/node_modules/@isaacs/cliui/node_modules/ansi-regex": { + "version": "6.0.1", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/npm/node_modules/@isaacs/cliui/node_modules/emoji-regex": { + "version": "9.2.2", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/@isaacs/cliui/node_modules/string-width": { + "version": "5.1.2", + "inBundle": true, + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm/node_modules/@isaacs/cliui/node_modules/strip-ansi": { + "version": "7.1.0", + "inBundle": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/npm/node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/npm/node_modules/@isaacs/string-locale-compare": { + "version": "1.1.0", + "inBundle": true, + "license": "ISC" + }, + "node_modules/npm/node_modules/@npmcli/agent": { + "version": "3.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "agent-base": "^7.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.1", + "lru-cache": "^10.0.1", + "socks-proxy-agent": "^8.0.3" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/arborist": { + "version": "8.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@isaacs/string-locale-compare": "^1.1.0", + "@npmcli/fs": "^4.0.0", + "@npmcli/installed-package-contents": "^3.0.0", + "@npmcli/map-workspaces": "^4.0.1", + "@npmcli/metavuln-calculator": "^8.0.0", + "@npmcli/name-from-folder": "^3.0.0", + "@npmcli/node-gyp": "^4.0.0", + "@npmcli/package-json": "^6.0.1", + "@npmcli/query": "^4.0.0", + "@npmcli/redact": "^3.0.0", + "@npmcli/run-script": "^9.0.1", + "bin-links": "^5.0.0", + "cacache": "^19.0.1", + "common-ancestor-path": "^1.0.1", + "hosted-git-info": "^8.0.0", + "json-parse-even-better-errors": "^4.0.0", + "json-stringify-nice": "^1.1.4", + "lru-cache": "^10.2.2", + "minimatch": "^9.0.4", + "nopt": "^8.0.0", + "npm-install-checks": "^7.1.0", + "npm-package-arg": "^12.0.0", + "npm-pick-manifest": "^10.0.0", + "npm-registry-fetch": "^18.0.1", + "pacote": "^19.0.0", + "parse-conflict-json": "^4.0.0", + "proc-log": "^5.0.0", + "proggy": "^3.0.0", + "promise-all-reject-late": "^1.0.0", + "promise-call-limit": "^3.0.1", + "read-package-json-fast": "^4.0.0", + "semver": "^7.3.7", + "ssri": "^12.0.0", + "treeverse": "^3.0.0", + "walk-up-path": "^3.0.1" + }, + "bin": { + "arborist": "bin/index.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/config": { + "version": "9.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/map-workspaces": "^4.0.1", + "@npmcli/package-json": "^6.0.1", + "ci-info": "^4.0.0", + "ini": "^5.0.0", + "nopt": "^8.0.0", + "proc-log": "^5.0.0", + "semver": "^7.3.5", + "walk-up-path": "^3.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/fs": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/git": { + "version": "6.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/promise-spawn": "^8.0.0", + "ini": "^5.0.0", + "lru-cache": "^10.0.1", + "npm-pick-manifest": "^10.0.0", + "proc-log": "^5.0.0", + "promise-inflight": "^1.0.1", + "promise-retry": "^2.0.1", + "semver": "^7.3.5", + "which": "^5.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/installed-package-contents": { + "version": "3.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "npm-bundled": "^4.0.0", + "npm-normalize-package-bin": "^4.0.0" + }, + "bin": { + "installed-package-contents": "bin/index.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/map-workspaces": { + "version": "4.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/name-from-folder": "^3.0.0", + "@npmcli/package-json": "^6.0.0", + "glob": "^10.2.2", + "minimatch": "^9.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/metavuln-calculator": { + "version": "8.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "cacache": "^19.0.0", + "json-parse-even-better-errors": "^4.0.0", + "pacote": "^19.0.0", + "proc-log": "^5.0.0", + "semver": "^7.3.5" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/name-from-folder": { + "version": "3.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/node-gyp": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/package-json": { + "version": "6.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/git": "^6.0.0", + "glob": "^10.2.2", + "hosted-git-info": "^8.0.0", + "json-parse-even-better-errors": "^4.0.0", + "normalize-package-data": "^7.0.0", + "proc-log": "^5.0.0", + "semver": "^7.5.3" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/promise-spawn": { + "version": "8.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "which": "^5.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/query": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "postcss-selector-parser": "^6.1.2" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/redact": { + "version": "3.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@npmcli/run-script": { + "version": "9.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/node-gyp": "^4.0.0", + "@npmcli/package-json": "^6.0.0", + "@npmcli/promise-spawn": "^8.0.0", + "node-gyp": "^10.0.0", + "proc-log": "^5.0.0", + "which": "^5.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/@pkgjs/parseargs": { + "version": "0.11.0", + "inBundle": true, + "license": "MIT", + "optional": true, + "engines": { + "node": ">=14" + } + }, + "node_modules/npm/node_modules/@sigstore/bundle": { + "version": "2.3.2", + "inBundle": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.3.2" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@sigstore/core": { + "version": "1.1.0", + "inBundle": true, + "license": "Apache-2.0", + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@sigstore/protobuf-specs": { + "version": "0.3.2", + "inBundle": true, + "license": "Apache-2.0", + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@sigstore/sign": { + "version": "2.3.2", + "inBundle": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^2.3.2", + "@sigstore/core": "^1.0.0", + "@sigstore/protobuf-specs": "^0.3.2", + "make-fetch-happen": "^13.0.1", + "proc-log": "^4.2.0", + "promise-retry": "^2.0.1" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@sigstore/sign/node_modules/@npmcli/agent": { + "version": "2.2.2", + "inBundle": true, + "license": "ISC", + "dependencies": { + "agent-base": "^7.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.1", + "lru-cache": "^10.0.1", + "socks-proxy-agent": "^8.0.3" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@sigstore/sign/node_modules/@npmcli/fs": { + "version": "3.1.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@sigstore/sign/node_modules/cacache": { + "version": "18.0.4", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/fs": "^3.1.0", + "fs-minipass": "^3.0.0", + "glob": "^10.2.2", + "lru-cache": "^10.0.1", + "minipass": "^7.0.3", + "minipass-collect": "^2.0.1", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "p-map": "^4.0.0", + "ssri": "^10.0.0", + "tar": "^6.1.11", + "unique-filename": "^3.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@sigstore/sign/node_modules/make-fetch-happen": { + "version": "13.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/agent": "^2.0.0", + "cacache": "^18.0.0", + "http-cache-semantics": "^4.1.1", + "is-lambda": "^1.0.1", + "minipass": "^7.0.2", + "minipass-fetch": "^3.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^0.6.3", + "proc-log": "^4.2.0", + "promise-retry": "^2.0.1", + "ssri": "^10.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@sigstore/sign/node_modules/minipass-fetch": { + "version": "3.0.5", + "inBundle": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.0.3", + "minipass-sized": "^1.0.3", + "minizlib": "^2.1.2" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + }, + "optionalDependencies": { + "encoding": "^0.1.13" + } + }, + "node_modules/npm/node_modules/@sigstore/sign/node_modules/proc-log": { + "version": "4.2.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@sigstore/sign/node_modules/ssri": { + "version": "10.0.6", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@sigstore/sign/node_modules/unique-filename": { + "version": "3.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "unique-slug": "^4.0.0" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@sigstore/sign/node_modules/unique-slug": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@sigstore/tuf": { + "version": "2.3.4", + "inBundle": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/protobuf-specs": "^0.3.2", + "tuf-js": "^2.2.1" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@sigstore/verify": { + "version": "1.2.1", + "inBundle": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^2.3.2", + "@sigstore/core": "^1.1.0", + "@sigstore/protobuf-specs": "^0.3.2" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@tufjs/canonical-json": { + "version": "2.0.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/@tufjs/models": { + "version": "2.0.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "@tufjs/canonical-json": "2.0.0", + "minimatch": "^9.0.4" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/abbrev": { + "version": "3.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/agent-base": { + "version": "7.1.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/npm/node_modules/aggregate-error": { + "version": "3.1.0", + "inBundle": true, + "license": "MIT", + "dependencies": { + "clean-stack": "^2.0.0", + "indent-string": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/ansi-regex": { + "version": "5.0.1", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/ansi-styles": { + "version": "6.2.1", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/npm/node_modules/aproba": { + "version": "2.0.0", + "inBundle": true, + "license": "ISC" + }, + "node_modules/npm/node_modules/archy": { + "version": "1.0.0", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/balanced-match": { + "version": "1.0.2", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/bin-links": { + "version": "5.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "cmd-shim": "^7.0.0", + "npm-normalize-package-bin": "^4.0.0", + "proc-log": "^5.0.0", + "read-cmd-shim": "^5.0.0", + "write-file-atomic": "^6.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/binary-extensions": { + "version": "2.3.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm/node_modules/brace-expansion": { + "version": "2.0.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/npm/node_modules/cacache": { + "version": "19.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/fs": "^4.0.0", + "fs-minipass": "^3.0.0", + "glob": "^10.2.2", + "lru-cache": "^10.0.1", + "minipass": "^7.0.3", + "minipass-collect": "^2.0.1", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "p-map": "^7.0.2", + "ssri": "^12.0.0", + "tar": "^7.4.3", + "unique-filename": "^4.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/cacache/node_modules/chownr": { + "version": "3.0.0", + "inBundle": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/npm/node_modules/cacache/node_modules/minizlib": { + "version": "3.0.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.0.4", + "rimraf": "^5.0.5" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/npm/node_modules/cacache/node_modules/mkdirp": { + "version": "3.0.1", + "inBundle": true, + "license": "MIT", + "bin": { + "mkdirp": "dist/cjs/src/bin.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/npm/node_modules/cacache/node_modules/p-map": { + "version": "7.0.2", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm/node_modules/cacache/node_modules/tar": { + "version": "7.4.3", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.0.1", + "mkdirp": "^3.0.1", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/npm/node_modules/cacache/node_modules/yallist": { + "version": "5.0.0", + "inBundle": true, + "license": "BlueOak-1.0.0", + "engines": { + "node": ">=18" + } + }, + "node_modules/npm/node_modules/chalk": { + "version": "5.3.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/npm/node_modules/chownr": { + "version": "2.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": ">=10" + } + }, + "node_modules/npm/node_modules/ci-info": { + "version": "4.0.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/sibiraj-s" + } + ], + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/cidr-regex": { + "version": "4.1.1", + "inBundle": true, + "license": "BSD-2-Clause", + "dependencies": { + "ip-regex": "^5.0.0" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/npm/node_modules/clean-stack": { + "version": "2.2.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/npm/node_modules/cli-columns": { + "version": "4.0.0", + "inBundle": true, + "license": "MIT", + "dependencies": { + "string-width": "^4.2.3", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/npm/node_modules/cmd-shim": { + "version": "7.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/color-convert": { + "version": "2.0.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/npm/node_modules/color-name": { + "version": "1.1.4", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/common-ancestor-path": { + "version": "1.0.1", + "inBundle": true, + "license": "ISC" + }, + "node_modules/npm/node_modules/cross-spawn": { + "version": "7.0.3", + "inBundle": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/npm/node_modules/cross-spawn/node_modules/which": { + "version": "2.0.2", + "inBundle": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/npm/node_modules/cssesc": { + "version": "3.0.0", + "inBundle": true, + "license": "MIT", + "bin": { + "cssesc": "bin/cssesc" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/npm/node_modules/debug": { + "version": "4.3.6", + "inBundle": true, + "license": "MIT", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/npm/node_modules/debug/node_modules/ms": { + "version": "2.1.2", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/diff": { + "version": "5.2.0", + "inBundle": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/npm/node_modules/eastasianwidth": { + "version": "0.2.0", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/emoji-regex": { + "version": "8.0.0", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/encoding": { + "version": "0.1.13", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "iconv-lite": "^0.6.2" + } + }, + "node_modules/npm/node_modules/env-paths": { + "version": "2.2.1", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/npm/node_modules/err-code": { + "version": "2.0.3", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/exponential-backoff": { + "version": "3.1.1", + "inBundle": true, + "license": "Apache-2.0" + }, + "node_modules/npm/node_modules/fastest-levenshtein": { + "version": "1.0.16", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">= 4.9.1" + } + }, + "node_modules/npm/node_modules/foreground-child": { + "version": "3.3.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "cross-spawn": "^7.0.0", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/npm/node_modules/fs-minipass": { + "version": "3.0.3", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/glob": { + "version": "10.4.5", + "inBundle": true, + "license": "ISC", + "dependencies": { + "foreground-child": "^3.1.0", + "jackspeak": "^3.1.2", + "minimatch": "^9.0.4", + "minipass": "^7.1.2", + "package-json-from-dist": "^1.0.0", + "path-scurry": "^1.11.1" + }, + "bin": { + "glob": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/npm/node_modules/graceful-fs": { + "version": "4.2.11", + "inBundle": true, + "license": "ISC" + }, + "node_modules/npm/node_modules/hosted-git-info": { + "version": "8.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "lru-cache": "^10.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/http-cache-semantics": { + "version": "4.1.1", + "inBundle": true, + "license": "BSD-2-Clause" + }, + "node_modules/npm/node_modules/http-proxy-agent": { + "version": "7.0.2", + "inBundle": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/npm/node_modules/https-proxy-agent": { + "version": "7.0.5", + "inBundle": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.0.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/npm/node_modules/iconv-lite": { + "version": "0.6.3", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/npm/node_modules/ignore-walk": { + "version": "7.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minimatch": "^9.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/imurmurhash": { + "version": "0.1.4", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/npm/node_modules/indent-string": { + "version": "4.0.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/ini": { + "version": "5.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/init-package-json": { + "version": "7.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/package-json": "^6.0.0", + "npm-package-arg": "^12.0.0", + "promzard": "^2.0.0", + "read": "^4.0.0", + "semver": "^7.3.5", + "validate-npm-package-license": "^3.0.4", + "validate-npm-package-name": "^6.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/ip-address": { + "version": "9.0.5", + "inBundle": true, + "license": "MIT", + "dependencies": { + "jsbn": "1.1.0", + "sprintf-js": "^1.1.3" + }, + "engines": { + "node": ">= 12" + } + }, + "node_modules/npm/node_modules/ip-regex": { + "version": "5.0.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm/node_modules/is-cidr": { + "version": "5.1.0", + "inBundle": true, + "license": "BSD-2-Clause", + "dependencies": { + "cidr-regex": "^4.1.1" + }, + "engines": { + "node": ">=14" + } + }, + "node_modules/npm/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/is-lambda": { + "version": "1.0.1", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/isexe": { + "version": "2.0.0", + "inBundle": true, + "license": "ISC" + }, + "node_modules/npm/node_modules/jackspeak": { + "version": "3.4.3", + "inBundle": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/cliui": "^8.0.2" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + }, + "optionalDependencies": { + "@pkgjs/parseargs": "^0.11.0" + } + }, + "node_modules/npm/node_modules/jsbn": { + "version": "1.1.0", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/json-parse-even-better-errors": { + "version": "4.0.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/json-stringify-nice": { + "version": "1.1.4", + "inBundle": true, + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/npm/node_modules/jsonparse": { + "version": "1.3.1", + "engines": [ + "node >= 0.2.0" + ], + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/just-diff": { + "version": "6.0.2", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/just-diff-apply": { + "version": "5.5.0", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/libnpmaccess": { + "version": "9.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "npm-package-arg": "^12.0.0", + "npm-registry-fetch": "^18.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/libnpmdiff": { + "version": "7.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/arborist": "^8.0.0", + "@npmcli/installed-package-contents": "^3.0.0", + "binary-extensions": "^2.3.0", + "diff": "^5.1.0", + "minimatch": "^9.0.4", + "npm-package-arg": "^12.0.0", + "pacote": "^19.0.0", + "tar": "^6.2.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/libnpmexec": { + "version": "9.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/arborist": "^8.0.0", + "@npmcli/run-script": "^9.0.1", + "ci-info": "^4.0.0", + "npm-package-arg": "^12.0.0", + "pacote": "^19.0.0", + "proc-log": "^5.0.0", + "read": "^4.0.0", + "read-package-json-fast": "^4.0.0", + "semver": "^7.3.7", + "walk-up-path": "^3.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/libnpmfund": { + "version": "6.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/arborist": "^8.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/libnpmhook": { + "version": "11.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "aproba": "^2.0.0", + "npm-registry-fetch": "^18.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/libnpmorg": { + "version": "7.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "aproba": "^2.0.0", + "npm-registry-fetch": "^18.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/libnpmpack": { + "version": "8.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/arborist": "^8.0.0", + "@npmcli/run-script": "^9.0.1", + "npm-package-arg": "^12.0.0", + "pacote": "^19.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/libnpmpublish": { + "version": "10.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "ci-info": "^4.0.0", + "normalize-package-data": "^7.0.0", + "npm-package-arg": "^12.0.0", + "npm-registry-fetch": "^18.0.1", + "proc-log": "^5.0.0", + "semver": "^7.3.7", + "sigstore": "^2.2.0", + "ssri": "^12.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/libnpmsearch": { + "version": "8.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "npm-registry-fetch": "^18.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/libnpmteam": { + "version": "7.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "aproba": "^2.0.0", + "npm-registry-fetch": "^18.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/libnpmversion": { + "version": "7.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/git": "^6.0.1", + "@npmcli/run-script": "^9.0.1", + "json-parse-even-better-errors": "^4.0.0", + "proc-log": "^5.0.0", + "semver": "^7.3.7" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/lru-cache": { + "version": "10.4.3", + "inBundle": true, + "license": "ISC" + }, + "node_modules/npm/node_modules/make-fetch-happen": { + "version": "14.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/agent": "^3.0.0", + "cacache": "^19.0.1", + "http-cache-semantics": "^4.1.1", + "minipass": "^7.0.2", + "minipass-fetch": "^4.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^0.6.3", + "proc-log": "^5.0.0", + "promise-retry": "^2.0.1", + "ssri": "^12.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/minimatch": { + "version": "9.0.5", + "inBundle": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/npm/node_modules/minipass": { + "version": "7.1.2", + "inBundle": true, + "license": "ISC", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/npm/node_modules/minipass-collect": { + "version": "2.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/npm/node_modules/minipass-fetch": { + "version": "4.0.0", + "inBundle": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.0.3", + "minipass-sized": "^1.0.3", + "minizlib": "^3.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + }, + "optionalDependencies": { + "encoding": "^0.1.13" + } + }, + "node_modules/npm/node_modules/minipass-fetch/node_modules/minizlib": { + "version": "3.0.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.0.4", + "rimraf": "^5.0.5" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/npm/node_modules/minipass-flush": { + "version": "1.0.5", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/npm/node_modules/minipass-flush/node_modules/minipass": { + "version": "3.3.6", + "inBundle": true, + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/minipass-pipeline": { + "version": "1.2.4", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/minipass-pipeline/node_modules/minipass": { + "version": "3.3.6", + "inBundle": true, + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/minipass-sized": { + "version": "1.0.3", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/minipass-sized/node_modules/minipass": { + "version": "3.3.6", + "inBundle": true, + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/minizlib": { + "version": "2.1.2", + "inBundle": true, + "license": "MIT", + "dependencies": { + "minipass": "^3.0.0", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/npm/node_modules/minizlib/node_modules/minipass": { + "version": "3.3.6", + "inBundle": true, + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/mkdirp": { + "version": "1.0.4", + "inBundle": true, + "license": "MIT", + "bin": { + "mkdirp": "bin/cmd.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/npm/node_modules/ms": { + "version": "2.1.3", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/mute-stream": { + "version": "2.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/negotiator": { + "version": "0.6.3", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/npm/node_modules/node-gyp": { + "version": "10.2.0", + "inBundle": true, + "license": "MIT", + "dependencies": { + "env-paths": "^2.2.0", + "exponential-backoff": "^3.1.1", + "glob": "^10.3.10", + "graceful-fs": "^4.2.6", + "make-fetch-happen": "^13.0.0", + "nopt": "^7.0.0", + "proc-log": "^4.1.0", + "semver": "^7.3.5", + "tar": "^6.2.1", + "which": "^4.0.0" + }, + "bin": { + "node-gyp": "bin/node-gyp.js" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/node-gyp/node_modules/@npmcli/agent": { + "version": "2.2.2", + "inBundle": true, + "license": "ISC", + "dependencies": { + "agent-base": "^7.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.1", + "lru-cache": "^10.0.1", + "socks-proxy-agent": "^8.0.3" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/node-gyp/node_modules/@npmcli/fs": { + "version": "3.1.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/node-gyp/node_modules/abbrev": { + "version": "2.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/node-gyp/node_modules/cacache": { + "version": "18.0.4", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/fs": "^3.1.0", + "fs-minipass": "^3.0.0", + "glob": "^10.2.2", + "lru-cache": "^10.0.1", + "minipass": "^7.0.3", + "minipass-collect": "^2.0.1", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "p-map": "^4.0.0", + "ssri": "^10.0.0", + "tar": "^6.1.11", + "unique-filename": "^3.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/node-gyp/node_modules/isexe": { + "version": "3.1.1", + "inBundle": true, + "license": "ISC", + "engines": { + "node": ">=16" + } + }, + "node_modules/npm/node_modules/node-gyp/node_modules/make-fetch-happen": { + "version": "13.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/agent": "^2.0.0", + "cacache": "^18.0.0", + "http-cache-semantics": "^4.1.1", + "is-lambda": "^1.0.1", + "minipass": "^7.0.2", + "minipass-fetch": "^3.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^0.6.3", + "proc-log": "^4.2.0", + "promise-retry": "^2.0.1", + "ssri": "^10.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/node-gyp/node_modules/minipass-fetch": { + "version": "3.0.5", + "inBundle": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.0.3", + "minipass-sized": "^1.0.3", + "minizlib": "^2.1.2" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + }, + "optionalDependencies": { + "encoding": "^0.1.13" + } + }, + "node_modules/npm/node_modules/node-gyp/node_modules/nopt": { + "version": "7.2.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "abbrev": "^2.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/node-gyp/node_modules/proc-log": { + "version": "4.2.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/node-gyp/node_modules/ssri": { + "version": "10.0.6", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/node-gyp/node_modules/unique-filename": { + "version": "3.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "unique-slug": "^4.0.0" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/node-gyp/node_modules/unique-slug": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/node-gyp/node_modules/which": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/nopt": { + "version": "8.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "abbrev": "^2.0.0" + }, + "bin": { + "nopt": "bin/nopt.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/nopt/node_modules/abbrev": { + "version": "2.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/normalize-package-data": { + "version": "7.0.0", + "inBundle": true, + "license": "BSD-2-Clause", + "dependencies": { + "hosted-git-info": "^8.0.0", + "semver": "^7.3.5", + "validate-npm-package-license": "^3.0.4" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/npm-audit-report": { + "version": "6.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/npm-bundled": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "npm-normalize-package-bin": "^4.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/npm-install-checks": { + "version": "7.1.0", + "inBundle": true, + "license": "BSD-2-Clause", + "dependencies": { + "semver": "^7.1.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/npm-normalize-package-bin": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/npm-package-arg": { + "version": "12.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "hosted-git-info": "^8.0.0", + "proc-log": "^5.0.0", + "semver": "^7.3.5", + "validate-npm-package-name": "^6.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/npm-packlist": { + "version": "9.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "ignore-walk": "^7.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/npm-pick-manifest": { + "version": "10.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "npm-install-checks": "^7.1.0", + "npm-normalize-package-bin": "^4.0.0", + "npm-package-arg": "^12.0.0", + "semver": "^7.3.5" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/npm-profile": { + "version": "11.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "npm-registry-fetch": "^18.0.0", + "proc-log": "^5.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/npm-registry-fetch": { + "version": "18.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/redact": "^3.0.0", + "jsonparse": "^1.3.1", + "make-fetch-happen": "^14.0.0", + "minipass": "^7.0.2", + "minipass-fetch": "^4.0.0", + "minizlib": "^3.0.1", + "npm-package-arg": "^12.0.0", + "proc-log": "^5.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/npm-registry-fetch/node_modules/minizlib": { + "version": "3.0.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.0.4", + "rimraf": "^5.0.5" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/npm/node_modules/npm-user-validate": { + "version": "3.0.0", + "inBundle": true, + "license": "BSD-2-Clause", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/p-map": { + "version": "4.0.0", + "inBundle": true, + "license": "MIT", + "dependencies": { + "aggregate-error": "^3.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm/node_modules/package-json-from-dist": { + "version": "1.0.0", + "inBundle": true, + "license": "BlueOak-1.0.0" + }, + "node_modules/npm/node_modules/pacote": { + "version": "19.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/git": "^6.0.0", + "@npmcli/installed-package-contents": "^3.0.0", + "@npmcli/package-json": "^6.0.0", + "@npmcli/promise-spawn": "^8.0.0", + "@npmcli/run-script": "^9.0.0", + "cacache": "^19.0.0", + "fs-minipass": "^3.0.0", + "minipass": "^7.0.2", + "npm-package-arg": "^12.0.0", + "npm-packlist": "^9.0.0", + "npm-pick-manifest": "^10.0.0", + "npm-registry-fetch": "^18.0.0", + "proc-log": "^5.0.0", + "promise-retry": "^2.0.1", + "sigstore": "^2.2.0", + "ssri": "^12.0.0", + "tar": "^6.1.11" + }, + "bin": { + "pacote": "bin/index.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/parse-conflict-json": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "json-parse-even-better-errors": "^4.0.0", + "just-diff": "^6.0.0", + "just-diff-apply": "^5.2.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/path-key": { + "version": "3.1.1", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/path-scurry": { + "version": "1.11.1", + "inBundle": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/npm/node_modules/postcss-selector-parser": { + "version": "6.1.2", + "inBundle": true, + "license": "MIT", + "dependencies": { + "cssesc": "^3.0.0", + "util-deprecate": "^1.0.2" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/npm/node_modules/proc-log": { + "version": "5.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/proggy": { + "version": "3.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/promise-all-reject-late": { + "version": "1.0.1", + "inBundle": true, + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/npm/node_modules/promise-call-limit": { + "version": "3.0.1", + "inBundle": true, + "license": "ISC", + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/npm/node_modules/promise-inflight": { + "version": "1.0.1", + "inBundle": true, + "license": "ISC" + }, + "node_modules/npm/node_modules/promise-retry": { + "version": "2.0.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "err-code": "^2.0.2", + "retry": "^0.12.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/npm/node_modules/promzard": { + "version": "2.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "read": "^4.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/qrcode-terminal": { + "version": "0.12.0", + "inBundle": true, + "bin": { + "qrcode-terminal": "bin/qrcode-terminal.js" + } + }, + "node_modules/npm/node_modules/read": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "mute-stream": "^2.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/read-cmd-shim": { + "version": "5.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/read-package-json-fast": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "json-parse-even-better-errors": "^4.0.0", + "npm-normalize-package-bin": "^4.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/retry": { + "version": "0.12.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/npm/node_modules/rimraf": { + "version": "5.0.10", + "inBundle": true, + "license": "ISC", + "dependencies": { + "glob": "^10.3.7" + }, + "bin": { + "rimraf": "dist/esm/bin.mjs" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/npm/node_modules/safer-buffer": { + "version": "2.1.2", + "inBundle": true, + "license": "MIT", + "optional": true + }, + "node_modules/npm/node_modules/semver": { + "version": "7.6.3", + "inBundle": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/npm/node_modules/shebang-command": { + "version": "2.0.0", + "inBundle": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/shebang-regex": { + "version": "3.0.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/signal-exit": { + "version": "4.1.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/npm/node_modules/sigstore": { + "version": "2.3.1", + "inBundle": true, + "license": "Apache-2.0", + "dependencies": { + "@sigstore/bundle": "^2.3.2", + "@sigstore/core": "^1.0.0", + "@sigstore/protobuf-specs": "^0.3.2", + "@sigstore/sign": "^2.3.2", + "@sigstore/tuf": "^2.3.4", + "@sigstore/verify": "^1.2.1" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/smart-buffer": { + "version": "4.2.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/npm/node_modules/socks": { + "version": "2.8.3", + "inBundle": true, + "license": "MIT", + "dependencies": { + "ip-address": "^9.0.5", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/npm/node_modules/socks-proxy-agent": { + "version": "8.0.4", + "inBundle": true, + "license": "MIT", + "dependencies": { + "agent-base": "^7.1.1", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/npm/node_modules/spdx-correct": { + "version": "3.2.0", + "inBundle": true, + "license": "Apache-2.0", + "dependencies": { + "spdx-expression-parse": "^3.0.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/npm/node_modules/spdx-correct/node_modules/spdx-expression-parse": { + "version": "3.0.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/npm/node_modules/spdx-exceptions": { + "version": "2.5.0", + "inBundle": true, + "license": "CC-BY-3.0" + }, + "node_modules/npm/node_modules/spdx-expression-parse": { + "version": "4.0.0", + "inBundle": true, + "license": "MIT", + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/npm/node_modules/spdx-license-ids": { + "version": "3.0.18", + "inBundle": true, + "license": "CC0-1.0" + }, + "node_modules/npm/node_modules/sprintf-js": { + "version": "1.1.3", + "inBundle": true, + "license": "BSD-3-Clause" + }, + "node_modules/npm/node_modules/ssri": { + "version": "12.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/string-width": { + "version": "4.2.3", + "inBundle": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "inBundle": true, + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/strip-ansi": { + "version": "6.0.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/supports-color": { + "version": "9.4.0", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/npm/node_modules/tar": { + "version": "6.2.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "chownr": "^2.0.0", + "fs-minipass": "^2.0.0", + "minipass": "^5.0.0", + "minizlib": "^2.1.1", + "mkdirp": "^1.0.3", + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/npm/node_modules/tar/node_modules/fs-minipass": { + "version": "2.1.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minipass": "^3.0.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/npm/node_modules/tar/node_modules/fs-minipass/node_modules/minipass": { + "version": "3.3.6", + "inBundle": true, + "license": "ISC", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/tar/node_modules/minipass": { + "version": "5.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": ">=8" + } + }, + "node_modules/npm/node_modules/text-table": { + "version": "0.2.0", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/tiny-relative-date": { + "version": "1.3.0", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/treeverse": { + "version": "3.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/tuf-js": { + "version": "2.2.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "@tufjs/models": "2.0.1", + "debug": "^4.3.4", + "make-fetch-happen": "^13.0.1" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/tuf-js/node_modules/@npmcli/agent": { + "version": "2.2.2", + "inBundle": true, + "license": "ISC", + "dependencies": { + "agent-base": "^7.1.0", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.1", + "lru-cache": "^10.0.1", + "socks-proxy-agent": "^8.0.3" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/tuf-js/node_modules/@npmcli/fs": { + "version": "3.1.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "semver": "^7.3.5" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/tuf-js/node_modules/cacache": { + "version": "18.0.4", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/fs": "^3.1.0", + "fs-minipass": "^3.0.0", + "glob": "^10.2.2", + "lru-cache": "^10.0.1", + "minipass": "^7.0.3", + "minipass-collect": "^2.0.1", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "p-map": "^4.0.0", + "ssri": "^10.0.0", + "tar": "^6.1.11", + "unique-filename": "^3.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/tuf-js/node_modules/make-fetch-happen": { + "version": "13.0.1", + "inBundle": true, + "license": "ISC", + "dependencies": { + "@npmcli/agent": "^2.0.0", + "cacache": "^18.0.0", + "http-cache-semantics": "^4.1.1", + "is-lambda": "^1.0.1", + "minipass": "^7.0.2", + "minipass-fetch": "^3.0.0", + "minipass-flush": "^1.0.5", + "minipass-pipeline": "^1.2.4", + "negotiator": "^0.6.3", + "proc-log": "^4.2.0", + "promise-retry": "^2.0.1", + "ssri": "^10.0.0" + }, + "engines": { + "node": "^16.14.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/tuf-js/node_modules/minipass-fetch": { + "version": "3.0.5", + "inBundle": true, + "license": "MIT", + "dependencies": { + "minipass": "^7.0.3", + "minipass-sized": "^1.0.3", + "minizlib": "^2.1.2" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + }, + "optionalDependencies": { + "encoding": "^0.1.13" + } + }, + "node_modules/npm/node_modules/tuf-js/node_modules/proc-log": { + "version": "4.2.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/tuf-js/node_modules/ssri": { + "version": "10.0.6", + "inBundle": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/tuf-js/node_modules/unique-filename": { + "version": "3.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "unique-slug": "^4.0.0" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/tuf-js/node_modules/unique-slug": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/npm/node_modules/unique-filename": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "unique-slug": "^5.0.0" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/unique-slug": { + "version": "5.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/util-deprecate": { + "version": "1.0.2", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/validate-npm-package-license": { + "version": "3.0.4", + "inBundle": true, + "license": "Apache-2.0", + "dependencies": { + "spdx-correct": "^3.0.0", + "spdx-expression-parse": "^3.0.0" + } + }, + "node_modules/npm/node_modules/validate-npm-package-license/node_modules/spdx-expression-parse": { + "version": "3.0.1", + "inBundle": true, + "license": "MIT", + "dependencies": { + "spdx-exceptions": "^2.1.0", + "spdx-license-ids": "^3.0.0" + } + }, + "node_modules/npm/node_modules/validate-npm-package-name": { + "version": "6.0.0", + "inBundle": true, + "license": "ISC", + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/walk-up-path": { + "version": "3.0.1", + "inBundle": true, + "license": "ISC" + }, + "node_modules/npm/node_modules/which": { + "version": "5.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "isexe": "^3.1.1" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/which/node_modules/isexe": { + "version": "3.1.1", + "inBundle": true, + "license": "ISC", + "engines": { + "node": ">=16" + } + }, + "node_modules/npm/node_modules/wrap-ansi": { + "version": "8.1.0", + "inBundle": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/npm/node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "inBundle": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/npm/node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "inBundle": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/npm/node_modules/wrap-ansi/node_modules/ansi-regex": { + "version": "6.0.1", + "inBundle": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/npm/node_modules/wrap-ansi/node_modules/emoji-regex": { + "version": "9.2.2", + "inBundle": true, + "license": "MIT" + }, + "node_modules/npm/node_modules/wrap-ansi/node_modules/string-width": { + "version": "5.1.2", + "inBundle": true, + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/npm/node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "7.1.0", + "inBundle": true, + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/npm/node_modules/write-file-atomic": { + "version": "6.0.0", + "inBundle": true, + "license": "ISC", + "dependencies": { + "imurmurhash": "^0.1.4", + "signal-exit": "^4.0.1" + }, + "engines": { + "node": "^18.17.0 || >=20.5.0" + } + }, + "node_modules/npm/node_modules/yallist": { + "version": "4.0.0", + "inBundle": true, + "license": "ISC" + }, + "node_modules/nth-check": { + "version": "2.1.1", + "license": "BSD-2-Clause", + "dependencies": { + "boolbase": "^1.0.0" + }, + "funding": { + "url": "https://github.com/fb55/nth-check?sponsor=1" + } + }, + "node_modules/num-sort": { + "version": "2.1.0", + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/once": { + "version": "1.4.0", + "license": "ISC", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/openai": { + "version": "4.67.1", + "license": "Apache-2.0", + "dependencies": { + "@types/node": "^18.11.18", + "@types/node-fetch": "^2.6.4", + "abort-controller": "^3.0.0", + "agentkeepalive": "^4.2.1", + "form-data-encoder": "1.7.2", + "formdata-node": "^4.3.2", + "node-fetch": "^2.6.7" + }, + "bin": { + "openai": "bin/cli" + }, + "peerDependencies": { + "zod": "^3.23.8" + }, + "peerDependenciesMeta": { + "zod": { + "optional": true + } + } + }, + "node_modules/openai/node_modules/@types/node": { + "version": "18.19.33", + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/openapi-types": { + "version": "12.1.3", + "license": "MIT" + }, + "node_modules/p-finally": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/p-queue": { + "version": "6.6.2", + "license": "MIT", + "dependencies": { + "eventemitter3": "^4.0.4", + "p-timeout": "^3.2.0" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-queue/node_modules/eventemitter3": { + "version": "4.0.7", + "license": "MIT" + }, + "node_modules/p-retry": { + "version": "4.6.2", + "license": "MIT", + "dependencies": { + "@types/retry": "0.12.0", + "retry": "^0.13.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/p-timeout": { + "version": "3.2.0", + "license": "MIT", + "dependencies": { + "p-finally": "^1.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/parse-json": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/parse-json/-/parse-json-5.2.0.tgz", + "integrity": "sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "@babel/code-frame": "^7.0.0", + "error-ex": "^1.3.1", + "json-parse-even-better-errors": "^2.3.0", + "lines-and-columns": "^1.1.6" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parse-json/node_modules/json-parse-even-better-errors": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz", + "integrity": "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w==", + "license": "MIT", + "optional": true, + "peer": true + }, + "node_modules/parse5": { + "version": "7.1.2", + "license": "MIT", + "dependencies": { + "entities": "^4.4.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-htmlparser2-tree-adapter": { + "version": "7.0.0", + "license": "MIT", + "dependencies": { + "domhandler": "^5.0.2", + "parse5": "^7.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5-parser-stream": { + "version": "7.1.2", + "license": "MIT", + "dependencies": { + "parse5": "^7.0.0" + }, + "funding": { + "url": "https://github.com/inikulin/parse5?sponsor=1" + } + }, + "node_modules/parse5/node_modules/entities": { + "version": "4.5.0", + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.12" + }, + "funding": { + "url": "https://github.com/fb55/entities?sponsor=1" + } + }, + "node_modules/parseley": { + "version": "0.12.1", + "license": "MIT", + "dependencies": { + "leac": "^0.6.0", + "peberminta": "^0.9.0" + }, + "funding": { + "url": "https://ko-fi.com/killymxi" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "license": "MIT" + }, + "node_modules/path-posix": { + "version": "1.0.0", + "license": "ISC" + }, + "node_modules/path-scurry": { + "version": "1.11.1", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^10.2.0", + "minipass": "^5.0.0 || ^6.0.2 || ^7.0.0" + }, + "engines": { + "node": ">=16 || 14 >=14.18" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-type": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/pause-stream": { + "version": "0.0.11", + "license": [ + "MIT", + "Apache2" + ], + "dependencies": { + "through": "~2.3" + } + }, + "node_modules/peberminta": { + "version": "0.9.0", + "license": "MIT", + "funding": { + "url": "https://ko-fi.com/killymxi" + } + }, + "node_modules/pend": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz", + "integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==", + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.0.tgz", + "integrity": "sha512-TQ92mBOW0l3LeMeyLV6mzy/kWr8lkd/hp3mTg7wYK7zJhuBStmGMBG0BdeDZS/dZx1IukaX6Bk11zcln25o1Aw==", + "license": "ISC", + "optional": true, + "peer": true + }, + "node_modules/picomatch": { + "version": "2.3.1", + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "license": "MIT", + "optional": true + }, + "node_modules/progress": { + "version": "2.0.3", + "license": "MIT", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/proto-list": { + "version": "1.2.4", + "license": "ISC" + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "license": "MIT" + }, + "node_modules/ps-tree": { + "version": "1.2.0", + "license": "MIT", + "dependencies": { + "event-stream": "=3.3.4" + }, + "bin": { + "ps-tree": "bin/ps-tree.js" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/pump": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.2.tgz", + "integrity": "sha512-tUPXtzlGM8FE3P0ZL6DVs/3P58k9nk8/jZeQCurTJylQA8qFYzHFfhBJkuqyE0FifOsQ0uKWekiZ5g8wtr28cw==", + "license": "MIT", + "dependencies": { + "end-of-stream": "^1.1.0", + "once": "^1.3.1" + } + }, + "node_modules/punycode.js": { + "version": "2.3.1", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=6" + } + }, + "node_modules/puppeteer": { + "version": "19.11.1", + "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-19.11.1.tgz", + "integrity": "sha512-39olGaX2djYUdhaQQHDZ0T0GwEp+5f9UB9HmEP0qHfdQHIq0xGQZuAZ5TLnJIc/88SrPLpEflPC+xUqOTv3c5g==", + "deprecated": "< 22.8.2 is no longer supported", + "hasInstallScript": true, + "license": "Apache-2.0", + "optional": true, + "peer": true, + "dependencies": { + "@puppeteer/browsers": "0.5.0", + "cosmiconfig": "8.1.3", + "https-proxy-agent": "5.0.1", + "progress": "2.0.3", + "proxy-from-env": "1.1.0", + "puppeteer-core": "19.11.1" + } + }, + "node_modules/puppeteer-core": { + "version": "19.11.1", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-19.11.1.tgz", + "integrity": "sha512-qcuC2Uf0Fwdj9wNtaTZ2OvYRraXpAK+puwwVW8ofOhOgLPZyz1c68tsorfIZyCUOpyBisjr+xByu7BMbEYMepA==", + "license": "Apache-2.0", + "optional": true, + "peer": true, + "dependencies": { + "@puppeteer/browsers": "0.5.0", + "chromium-bidi": "0.4.7", + "cross-fetch": "3.1.5", + "debug": "4.3.4", + "devtools-protocol": "0.0.1107588", + "extract-zip": "2.0.1", + "https-proxy-agent": "5.0.1", + "proxy-from-env": "1.1.0", + "tar-fs": "2.1.1", + "unbzip2-stream": "1.4.3", + "ws": "8.13.0" + }, + "engines": { + "node": ">=14.14.0" + }, + "peerDependencies": { + "typescript": ">= 4.7.4" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/puppeteer-core/node_modules/cross-fetch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.5.tgz", + "integrity": "sha512-lvb1SBsI0Z7GDwmuid+mU3kWVBwTVUbe7S0H52yaaAdQOXq2YktTCZdlAcNKFzE6QtRz0snpw9bNiPeOIkkQvw==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "node-fetch": "2.6.7" + } + }, + "node_modules/puppeteer-core/node_modules/node-fetch": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", + "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/puppeteer-core/node_modules/ws": { + "version": "8.13.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", + "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/pyodide": { + "version": "0.24.1", + "license": "Apache-2.0", + "dependencies": { + "base-64": "^1.0.0", + "ws": "^8.5.0" + } + }, + "node_modules/qrcode-terminal": { + "version": "0.12.0", + "bin": { + "qrcode-terminal": "bin/qrcode-terminal.js" + } + }, + "node_modules/query-string": { + "version": "7.1.3", + "license": "MIT", + "dependencies": { + "decode-uri-component": "^0.2.2", + "filter-obj": "^1.1.0", + "split-on-first": "^1.0.0", + "strict-uri-encode": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/querystringify": { + "version": "2.2.0", + "license": "MIT" + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/quickchart-js": { + "version": "3.1.3", + "license": "MIT", + "dependencies": { + "cross-fetch": "^3.1.5", + "javascript-stringify": "^2.1.0" + } + }, + "node_modules/react": { + "version": "18.3.1", + "license": "MIT", + "peer": true, + "dependencies": { + "loose-envify": "^1.1.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "18.3.1", + "license": "MIT", + "peer": true, + "dependencies": { + "loose-envify": "^1.1.0", + "scheduler": "^0.23.2" + }, + "peerDependencies": { + "react": "^18.3.1" + } + }, + "node_modules/react-promise-suspense": { + "version": "0.3.4", + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^2.0.1" + } + }, + "node_modules/react-promise-suspense/node_modules/fast-deep-equal": { + "version": "2.0.1", + "license": "MIT" + }, + "node_modules/readable-stream": { + "version": "1.1.14", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.1", + "isarray": "0.0.1", + "string_decoder": "~0.10.x" + } + }, + "node_modules/readdir-glob": { + "version": "1.1.3", + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "minimatch": "^5.1.0" + } + }, + "node_modules/readdir-glob/node_modules/minimatch": { + "version": "5.1.6", + "license": "ISC", + "optional": true, + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/readline-sync": { + "version": "1.4.10", + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/rechoir": { + "version": "0.6.2", + "dependencies": { + "resolve": "^1.1.6" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/ref-napi": { + "version": "3.0.3", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "debug": "^4.1.1", + "get-symbol-from-current-process-h": "^1.0.2", + "node-addon-api": "^3.0.0", + "node-gyp-build": "^4.2.1" + }, + "engines": { + "node": ">= 10.0" + } + }, + "node_modules/ref-struct-di": { + "version": "1.1.1", + "license": "MIT", + "dependencies": { + "debug": "^3.1.0" + } + }, + "node_modules/ref-struct-di/node_modules/debug": { + "version": "3.2.7", + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/regenerator-runtime": { + "version": "0.14.1", + "license": "MIT" + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/requires-port": { + "version": "1.0.0", + "license": "MIT" + }, + "node_modules/resend": { + "version": "4.0.0", + "license": "MIT", + "dependencies": { + "@react-email/render": "0.0.17" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/resolve": { + "version": "1.22.8", + "license": "MIT", + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "license": "MIT", + "optional": true, + "peer": true, + "engines": { + "node": ">=4" + } + }, + "node_modules/retry": { + "version": "0.13.1", + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/reusify": { + "version": "1.0.4", + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "license": "MIT", + "optional": true + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "license": "MIT" + }, + "node_modules/sax": { + "version": "1.4.1", + "license": "ISC" + }, + "node_modules/scheduler": { + "version": "0.23.2", + "license": "MIT", + "peer": true, + "dependencies": { + "loose-envify": "^1.1.0" + } + }, + "node_modules/seedrandom": { + "version": "3.0.5", + "license": "MIT" + }, + "node_modules/selderee": { + "version": "0.11.0", + "license": "MIT", + "dependencies": { + "parseley": "^0.12.0" + }, + "funding": { + "url": "https://ko-fi.com/killymxi" + } + }, + "node_modules/semver": { + "version": "7.6.3", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/serpapi": { + "version": "2.1.0", + "license": "MIT" + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/setimmediate": { + "version": "1.0.5", + "license": "MIT", + "optional": true + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/shelljs": { + "version": "0.8.5", + "license": "BSD-3-Clause", + "dependencies": { + "glob": "^7.0.0", + "interpret": "^1.0.0", + "rechoir": "^0.6.2" + }, + "bin": { + "shjs": "bin/shjs" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/shelljs/node_modules/glob": { + "version": "7.2.3", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/shelljs/node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/shelljs/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion": { + "version": "1.1.11", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/shiki": { + "version": "1.13.0", + "license": "MIT", + "peer": true, + "dependencies": { + "@shikijs/core": "1.13.0", + "@types/hast": "^3.0.4" + } + }, + "node_modules/signal-exit": { + "version": "4.1.0", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/slash": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/source-map-support": { + "version": "0.5.21", + "license": "MIT", + "dependencies": { + "buffer-from": "^1.0.0", + "source-map": "^0.6.0" + } + }, + "node_modules/split": { + "version": "0.3.3", + "license": "MIT", + "dependencies": { + "through": "2" + }, + "engines": { + "node": "*" + } + }, + "node_modules/split-on-first": { + "version": "1.1.0", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/stream-chain": { + "version": "2.2.5", + "license": "BSD-3-Clause" + }, + "node_modules/stream-combiner": { + "version": "0.0.4", + "license": "MIT", + "dependencies": { + "duplexer": "~0.1.1" + } + }, + "node_modules/stream-json": { + "version": "1.8.0", + "license": "BSD-3-Clause", + "dependencies": { + "stream-chain": "^2.2.5" + } + }, + "node_modules/stream-parser": { + "version": "0.3.1", + "license": "MIT", + "dependencies": { + "debug": "2" + } + }, + "node_modules/stream-parser/node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/stream-parser/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/strict-uri-encode": { + "version": "2.0.0", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/string_decoder": { + "version": "0.10.31", + "license": "MIT" + }, + "node_modules/string-width": { + "version": "4.2.3", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/string-width-cjs": { + "name": "string-width", + "version": "4.2.3", + "license": "MIT", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi-cjs": { + "name": "strip-ansi", + "version": "6.0.1", + "license": "MIT", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strnum": { + "version": "1.0.5", + "license": "MIT" + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tar-fs": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/tar-fs/-/tar-fs-2.1.1.tgz", + "integrity": "sha512-V0r2Y9scmbDRLCNex/+hYzvp/zyYjvFbHPNgVTKfQvVrb6guiE/fxP+XblDNR011utopbkex2nM4dHNV6GDsng==", + "license": "MIT", + "dependencies": { + "chownr": "^1.1.1", + "mkdirp-classic": "^0.5.2", + "pump": "^3.0.0", + "tar-stream": "^2.1.4" + } + }, + "node_modules/tar-fs/node_modules/chownr": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-1.1.4.tgz", + "integrity": "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==", + "license": "ISC" + }, + "node_modules/tar-stream": { + "version": "2.2.0", + "license": "MIT", + "dependencies": { + "bl": "^4.0.3", + "end-of-stream": "^1.4.1", + "fs-constants": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^3.1.1" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/tar-stream/node_modules/readable-stream": { + "version": "3.6.2", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/tar-stream/node_modules/readable-stream/node_modules/string_decoder": { + "version": "1.3.0", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/tar-stream/node_modules/readable-stream/node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/through": { + "version": "2.3.8", + "license": "MIT" + }, + "node_modules/through2": { + "version": "4.0.2", + "license": "MIT", + "dependencies": { + "readable-stream": "3" + } + }, + "node_modules/through2/node_modules/readable-stream": { + "version": "3.6.2", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/through2/node_modules/readable-stream/node_modules/string_decoder": { + "version": "1.3.0", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/through2/node_modules/readable-stream/node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/tiny-emitter": { + "version": "2.1.0", + "license": "MIT" + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/tr46": { + "version": "0.0.3", + "license": "MIT" + }, + "node_modules/traverse": { + "version": "0.3.9", + "license": "MIT/X11", + "optional": true + }, + "node_modules/ts-mixer": { + "version": "6.0.4", + "license": "MIT" + }, + "node_modules/tslib": { + "version": "2.7.0", + "license": "0BSD" + }, + "node_modules/tslog": { + "version": "2.12.0", + "license": "MIT", + "dependencies": { + "source-map-support": "^0.5.19" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/turndown": { + "version": "7.2.0", + "license": "MIT", + "dependencies": { + "@mixmark-io/domino": "^2.2.0" + } + }, + "node_modules/typed-function": { + "version": "4.2.1", + "license": "MIT", + "engines": { + "node": ">= 18" + } + }, + "node_modules/typedoc": { + "version": "0.26.5", + "license": "Apache-2.0", + "peer": true, + "dependencies": { + "lunr": "^2.3.9", + "markdown-it": "^14.1.0", + "minimatch": "^9.0.5", + "shiki": "^1.9.1", + "yaml": "^2.4.5" + }, + "bin": { + "typedoc": "bin/typedoc" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "typescript": "4.6.x || 4.7.x || 4.8.x || 4.9.x || 5.0.x || 5.1.x || 5.2.x || 5.3.x || 5.4.x || 5.5.x" + } + }, + "node_modules/typedoc-plugin-missing-exports": { + "version": "3.0.0", + "license": "MIT", + "peerDependencies": { + "typedoc": "0.26.x" + } + }, + "node_modules/typedoc/node_modules/yaml": { + "version": "2.5.0", + "license": "ISC", + "peer": true, + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/typescript": { + "version": "5.5.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz", + "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==", + "license": "Apache-2.0", + "peer": true, + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-event-target": { + "version": "1.1.1", + "license": "MIT" + }, + "node_modules/uc.micro": { + "version": "2.1.0", + "license": "MIT", + "peer": true + }, + "node_modules/uhyphen": { + "version": "0.2.0", + "license": "ISC" + }, + "node_modules/unbzip2-stream": { + "version": "1.4.3", + "resolved": "https://registry.npmjs.org/unbzip2-stream/-/unbzip2-stream-1.4.3.tgz", + "integrity": "sha512-mlExGW4w71ebDJviH16lQLtZS32VKqsSfk80GCfUlwT/4/hNRFsoscrF/c++9xinkMzECL1uL9DDwXqFWkruPg==", + "license": "MIT", + "dependencies": { + "buffer": "^5.2.1", + "through": "^2.3.8" + } + }, + "node_modules/undici": { + "version": "6.19.8", + "license": "MIT", + "engines": { + "node": ">=18.17" + } + }, + "node_modules/undici-types": { + "version": "5.26.5", + "license": "MIT" + }, + "node_modules/unfetch": { + "version": "4.2.0", + "license": "MIT" + }, + "node_modules/universalify": { + "version": "2.0.1", + "license": "MIT", + "engines": { + "node": ">= 10.0.0" + } + }, + "node_modules/unzipper": { + "version": "0.10.14", + "license": "MIT", + "optional": true, + "dependencies": { + "big-integer": "^1.6.17", + "binary": "~0.3.0", + "bluebird": "~3.4.1", + "buffer-indexof-polyfill": "~1.0.0", + "duplexer2": "~0.1.4", + "fstream": "^1.0.12", + "graceful-fs": "^4.2.2", + "listenercount": "~1.0.1", + "readable-stream": "~2.3.6", + "setimmediate": "~1.0.4" + } + }, + "node_modules/unzipper/node_modules/readable-stream": { + "version": "2.3.8", + "license": "MIT", + "optional": true, + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/unzipper/node_modules/readable-stream/node_modules/isarray": { + "version": "1.0.0", + "license": "MIT", + "optional": true + }, + "node_modules/unzipper/node_modules/readable-stream/node_modules/string_decoder": { + "version": "1.1.1", + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/url-join": { + "version": "5.0.0", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, + "node_modules/url-parse": { + "version": "1.5.10", + "license": "MIT", + "dependencies": { + "querystringify": "^2.1.1", + "requires-port": "^1.0.0" + } + }, + "node_modules/util": { + "version": "0.12.5", + "license": "MIT", + "dependencies": { + "inherits": "^2.0.3", + "is-arguments": "^1.0.4", + "is-generator-function": "^1.0.7", + "is-typed-array": "^1.1.3", + "which-typed-array": "^1.1.2" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "license": "MIT" + }, + "node_modules/uuid": { + "version": "9.0.1", + "funding": [ + "https://github.com/sponsors/broofa", + "https://github.com/sponsors/ctavan" + ], + "license": "MIT", + "bin": { + "uuid": "dist/bin/uuid" + } + }, + "node_modules/vcap_services": { + "version": "0.7.1", + "license": "MIT" + }, + "node_modules/vosk": { + "version": "0.3.39", + "license": "Apache-2.0", + "dependencies": { + "async": "^3.2.0", + "ffi-napi": "^4.0.3", + "mic": "^2.1.2", + "ref-napi": ">=2.0.0", + "wav": "^1.0.2" + }, + "engines": { + "node": ">= 12.x.x" + } + }, + "node_modules/vosk/node_modules/async": { + "version": "3.2.5", + "license": "MIT" + }, + "node_modules/wav": { + "version": "1.0.2", + "license": "MIT", + "dependencies": { + "buffer-alloc": "^1.1.0", + "buffer-from": "^1.0.0", + "debug": "^2.2.0", + "readable-stream": "^1.1.14", + "stream-parser": "^0.3.1" + } + }, + "node_modules/wav/node_modules/debug": { + "version": "2.6.9", + "license": "MIT", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/wav/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "license": "MIT" + }, + "node_modules/web-encoding": { + "version": "1.1.5", + "license": "MIT", + "dependencies": { + "util": "^0.12.3" + }, + "optionalDependencies": { + "@zxing/text-encoding": "0.9.0" + } + }, + "node_modules/web-streams-polyfill": { + "version": "3.3.3", + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/webdav": { + "version": "5.7.1", + "license": "MIT", + "dependencies": { + "@buttercup/fetch": "^0.2.1", + "base-64": "^1.0.0", + "byte-length": "^1.0.2", + "entities": "^5.0.0", + "fast-xml-parser": "^4.4.1", + "hot-patcher": "^2.0.1", + "layerr": "^3.0.0", + "md5": "^2.3.0", + "minimatch": "^9.0.5", + "nested-property": "^4.0.0", + "node-fetch": "^3.3.2", + "path-posix": "^1.0.0", + "url-join": "^5.0.0", + "url-parse": "^1.5.10" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/webdav/node_modules/node-fetch": { + "version": "3.3.2", + "license": "MIT", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/webidl-conversions": { + "version": "3.0.1", + "license": "BSD-2-Clause" + }, + "node_modules/webpod": { + "version": "0.0.2", + "license": "MIT", + "bin": { + "webpod": "dist/index.js" + } + }, + "node_modules/whatsapp-web.js": { + "version": "1.26.0", + "license": "Apache-2.0", + "dependencies": { + "@pedroslopez/moduleraid": "^5.0.2", + "fluent-ffmpeg": "2.1.2", + "mime": "^3.0.0", + "node-fetch": "^2.6.9", + "node-webpmux": "3.1.7", + "puppeteer": "^18.2.1" + }, + "engines": { + "node": ">=18.0.0" + }, + "optionalDependencies": { + "archiver": "^5.3.1", + "fs-extra": "^10.1.0", + "unzipper": "^0.10.11" + } + }, + "node_modules/whatsapp-web.js/node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/whatsapp-web.js/node_modules/cross-fetch": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/cross-fetch/-/cross-fetch-3.1.5.tgz", + "integrity": "sha512-lvb1SBsI0Z7GDwmuid+mU3kWVBwTVUbe7S0H52yaaAdQOXq2YktTCZdlAcNKFzE6QtRz0snpw9bNiPeOIkkQvw==", + "license": "MIT", + "dependencies": { + "node-fetch": "2.6.7" + } + }, + "node_modules/whatsapp-web.js/node_modules/cross-fetch/node_modules/node-fetch": { + "version": "2.6.7", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.7.tgz", + "integrity": "sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==", + "license": "MIT", + "dependencies": { + "whatwg-url": "^5.0.0" + }, + "engines": { + "node": "4.x || >=6.0.0" + }, + "peerDependencies": { + "encoding": "^0.1.0" + }, + "peerDependenciesMeta": { + "encoding": { + "optional": true + } + } + }, + "node_modules/whatsapp-web.js/node_modules/devtools-protocol": { + "version": "0.0.1045489", + "resolved": "https://registry.npmjs.org/devtools-protocol/-/devtools-protocol-0.0.1045489.tgz", + "integrity": "sha512-D+PTmWulkuQW4D1NTiCRCFxF7pQPn0hgp4YyX4wAQ6xYXKOadSWPR3ENGDQ47MW/Ewc9v2rpC/UEEGahgBYpSQ==", + "license": "BSD-3-Clause" + }, + "node_modules/whatsapp-web.js/node_modules/fluent-ffmpeg": { + "version": "2.1.2", + "license": "MIT", + "dependencies": { + "async": ">=0.2.9", + "which": "^1.1.1" + }, + "engines": { + "node": ">=0.8.0" + } + }, + "node_modules/whatsapp-web.js/node_modules/fluent-ffmpeg/node_modules/async": { + "version": "3.2.5", + "license": "MIT" + }, + "node_modules/whatsapp-web.js/node_modules/glob": { + "version": "7.2.3", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", + "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", + "deprecated": "Glob versions prior to v9 are no longer supported", + "license": "ISC", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/whatsapp-web.js/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/whatsapp-web.js/node_modules/puppeteer": { + "version": "18.2.1", + "resolved": "https://registry.npmjs.org/puppeteer/-/puppeteer-18.2.1.tgz", + "integrity": "sha512-7+UhmYa7wxPh2oMRwA++k8UGVDxh3YdWFB52r9C3tM81T6BU7cuusUSxImz0GEYSOYUKk/YzIhkQ6+vc0gHbxQ==", + "deprecated": "< 22.8.2 is no longer supported", + "hasInstallScript": true, + "license": "Apache-2.0", + "dependencies": { + "https-proxy-agent": "5.0.1", + "progress": "2.0.3", + "proxy-from-env": "1.1.0", + "puppeteer-core": "18.2.1" + }, + "engines": { + "node": ">=14.1.0" + } + }, + "node_modules/whatsapp-web.js/node_modules/puppeteer-core": { + "version": "18.2.1", + "resolved": "https://registry.npmjs.org/puppeteer-core/-/puppeteer-core-18.2.1.tgz", + "integrity": "sha512-MRtTAZfQTluz3U2oU/X2VqVWPcR1+94nbA2V6ZrSZRVEwLqZ8eclZ551qGFQD/vD2PYqHJwWOW/fpC721uznVw==", + "license": "Apache-2.0", + "dependencies": { + "cross-fetch": "3.1.5", + "debug": "4.3.4", + "devtools-protocol": "0.0.1045489", + "extract-zip": "2.0.1", + "https-proxy-agent": "5.0.1", + "proxy-from-env": "1.1.0", + "rimraf": "3.0.2", + "tar-fs": "2.1.1", + "unbzip2-stream": "1.4.3", + "ws": "8.9.0" + }, + "engines": { + "node": ">=14.1.0" + } + }, + "node_modules/whatsapp-web.js/node_modules/rimraf": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", + "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", + "deprecated": "Rimraf versions prior to v4 are no longer supported", + "license": "ISC", + "dependencies": { + "glob": "^7.1.3" + }, + "bin": { + "rimraf": "bin.js" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/whatsapp-web.js/node_modules/ws": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.9.0.tgz", + "integrity": "sha512-Ja7nszREasGaYUYCI2k4lCKIRTt+y7XuqVoHR44YpI49TtryyqbqvDMn5eqfW7e6HzTukDRIsXqzVHScqRcafg==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/whatwg-encoding": { + "version": "3.1.1", + "license": "MIT", + "dependencies": { + "iconv-lite": "0.6.3" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-mimetype": { + "version": "4.0.0", + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/whatwg-url": { + "version": "5.0.0", + "license": "MIT", + "dependencies": { + "tr46": "~0.0.3", + "webidl-conversions": "^3.0.0" + } + }, + "node_modules/which": { + "version": "1.3.1", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "which": "bin/which" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.15", + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/whisper-node": { + "version": "1.1.1", + "license": "MIT", + "dependencies": { + "readline-sync": "^1.4.10", + "shelljs": "^0.8.5" + }, + "bin": { + "download": "dist/download.js" + } + }, + "node_modules/wrap-ansi": { + "version": "8.1.0", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.1.0", + "string-width": "^5.0.1", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs": { + "name": "wrap-ansi", + "version": "7.0.0", + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi-cjs/node_modules/ansi-styles": { + "version": "4.3.0", + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "6.2.1", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "5.1.2", + "license": "MIT", + "dependencies": { + "eastasianwidth": "^0.2.0", + "emoji-regex": "^9.2.2", + "strip-ansi": "^7.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/wrap-ansi/node_modules/string-width/node_modules/emoji-regex": { + "version": "9.2.2", + "license": "MIT" + }, + "node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "7.1.0", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.0.1" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/strip-ansi/node_modules/ansi-regex": { + "version": "6.0.1", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "license": "ISC" + }, + "node_modules/ws": { + "version": "8.17.0", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/xml2js": { + "version": "0.6.2", + "license": "MIT", + "dependencies": { + "sax": ">=0.6.0", + "xmlbuilder": "~11.0.0" + }, + "engines": { + "node": ">=4.0.0" + } + }, + "node_modules/xmlbuilder": { + "version": "11.0.1", + "license": "MIT", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "license": "ISC", + "optional": true, + "peer": true, + "engines": { + "node": ">=10" + } + }, + "node_modules/yaml": { + "version": "2.4.2", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/yargs": { + "version": "17.7.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.1.tgz", + "integrity": "sha512-cwiTb08Xuv5fqF4AovYacTFNxk62th7LKJ6BL9IGUpTJrWoU7/7WdQGTP2SjKf1dUNBGzDd28p/Yfs/GI6JrLw==", + "license": "MIT", + "optional": true, + "peer": true, + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "license": "ISC", + "optional": true, + "peer": true, + "engines": { + "node": ">=12" + } + }, + "node_modules/yauzl": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz", + "integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==", + "license": "MIT", + "dependencies": { + "buffer-crc32": "~0.2.3", + "fd-slicer": "~1.1.0" + } + }, + "node_modules/yauzl/node_modules/buffer-crc32": { + "version": "0.2.13", + "resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz", + "integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==", + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/youtube-transcript": { + "version": "1.2.1", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/youtubei.js": { + "version": "5.8.0", + "funding": [ + "https://github.com/sponsors/LuanRT" + ], + "license": "MIT", + "dependencies": { + "jintr": "^1.1.0", + "linkedom": "^0.14.12", + "tslib": "^2.5.0", + "undici": "^5.19.1" + } + }, + "node_modules/youtubei.js/node_modules/tslib": { + "version": "2.6.2", + "license": "0BSD" + }, + "node_modules/youtubei.js/node_modules/undici": { + "version": "5.28.4", + "license": "MIT", + "dependencies": { + "@fastify/busboy": "^2.0.0" + }, + "engines": { + "node": ">=14.0" + } + }, + "node_modules/ytdl-core": { + "version": "4.11.5", + "license": "MIT", + "dependencies": { + "m3u8stream": "^0.8.6", + "miniget": "^4.2.2", + "sax": "^1.1.3" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/zip-stream": { + "version": "4.1.1", + "license": "MIT", + "optional": true, + "dependencies": { + "archiver-utils": "^3.0.4", + "compress-commons": "^4.1.2", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/zip-stream/node_modules/archiver-utils": { + "version": "3.0.4", + "license": "MIT", + "optional": true, + "dependencies": { + "glob": "^7.2.3", + "graceful-fs": "^4.2.0", + "lazystream": "^1.0.0", + "lodash.defaults": "^4.2.0", + "lodash.difference": "^4.5.0", + "lodash.flatten": "^4.4.0", + "lodash.isplainobject": "^4.0.6", + "lodash.union": "^4.6.0", + "normalize-path": "^3.0.0", + "readable-stream": "^3.6.0" + }, + "engines": { + "node": ">= 10" + } + }, + "node_modules/zip-stream/node_modules/archiver-utils/node_modules/glob": { + "version": "7.2.3", + "license": "ISC", + "optional": true, + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.1.1", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/zip-stream/node_modules/archiver-utils/node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "license": "ISC", + "optional": true, + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/zip-stream/node_modules/archiver-utils/node_modules/glob/node_modules/minimatch/node_modules/brace-expansion": { + "version": "1.1.11", + "license": "MIT", + "optional": true, + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/zip-stream/node_modules/readable-stream": { + "version": "3.6.2", + "license": "MIT", + "optional": true, + "dependencies": { + "inherits": "^2.0.3", + "string_decoder": "^1.1.1", + "util-deprecate": "^1.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/zip-stream/node_modules/readable-stream/node_modules/string_decoder": { + "version": "1.3.0", + "license": "MIT", + "optional": true, + "dependencies": { + "safe-buffer": "~5.2.0" + } + }, + "node_modules/zip-stream/node_modules/readable-stream/node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.2.1", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "optional": true + }, + "node_modules/zod": { + "version": "3.23.8", + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-to-json-schema": { + "version": "3.23.3", + "license": "ISC", + "peerDependencies": { + "zod": "^3.23.3" + } + }, + "node_modules/zx": { + "version": "7.2.3", + "license": "Apache-2.0", + "dependencies": { + "@types/fs-extra": "^11.0.1", + "@types/minimist": "^1.2.2", + "@types/node": "^18.16.3", + "@types/ps-tree": "^1.1.2", + "@types/which": "^3.0.0", + "chalk": "^5.2.0", + "fs-extra": "^11.1.1", + "fx": "*", + "globby": "^13.1.4", + "minimist": "^1.2.8", + "node-fetch": "3.3.1", + "ps-tree": "^1.2.0", + "webpod": "^0", + "which": "^3.0.0", + "yaml": "^2.2.2" + }, + "bin": { + "zx": "build/cli.js" + }, + "engines": { + "node": ">= 16.0.0" + } + }, + "node_modules/zx/node_modules/@types/node": { + "version": "18.19.33", + "license": "MIT", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/zx/node_modules/fs-extra": { + "version": "11.2.0", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^6.0.1", + "universalify": "^2.0.0" + }, + "engines": { + "node": ">=14.14" + } + }, + "node_modules/zx/node_modules/node-fetch": { + "version": "3.3.1", + "license": "MIT", + "dependencies": { + "data-uri-to-buffer": "^4.0.0", + "fetch-blob": "^3.1.4", + "formdata-polyfill": "^4.0.10" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/node-fetch" + } + }, + "node_modules/zx/node_modules/which": { + "version": "3.0.1", + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/which.js" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, + "node_modules/zx/node_modules/yaml": { + "version": "2.5.0", + "license": "ISC", + "bin": { + "yaml": "bin.mjs" + }, + "engines": { + "node": ">= 14" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..76700b6 --- /dev/null +++ b/package.json @@ -0,0 +1,57 @@ +{ + "name": "anya", + "module": "index.ts", + "type": "module", + "devDependencies": { + "@types/fluent-ffmpeg": "^2.1.24", + "bun-types": "latest" + }, + "scripts": { + "postinstall": "bunx @puppeteer/browsers install chrome@115.0.5790.98 --path $HOME/.cache/puppeteer" + }, + "peerDependencies": { + "typescript": "^5.0.0" + }, + "dependencies": { + "@dqbd/tiktoken": "^1.0.15", + "@nextcloud/files": "^3.8.0", + "@solyarisoftware/voskjs": "^1.2.8", + "@types/node-cron": "^3.0.11", + "@types/turndown": "^5.0.5", + "@types/xml2js": "^0.4.14", + "axios": "^1.7.3", + "cheerio": "^1.0.0-rc.12", + "date-fns": "^3.6.0", + "discord.js": "^14.14.1", + "elysia": "^1.1.17", + "fluent-ffmpeg": "^2.1.3", + "form-data": "^4.0.0", + "fuse.js": "^7.0.0", + "fuzzysort": "^3.0.2", + "i": "^0.3.7", + "langchain": "^0.0.212", + "mathjs": "^12.2.1", + "meta-fetcher": "^3.1.1", + "minio": "^8.0.1", + "nanoid": "^5.0.4", + "nextcloud-node-client": "^1.8.1", + "node-cron": "^3.0.3", + "npm": "^10.2.5", + "openai": "^4.67.1", + "pyodide": "^0.24.1", + "qrcode-terminal": "^0.12.0", + "quickchart-js": "^3.1.3", + "resend": "^4.0.0", + "serpapi": "^2.0.0", + "turndown": "^7.2.0", + "whatsapp-web.js": "^1.26.0", + "whisper-node": "^1.1.1", + "xml2js": "^0.6.2", + "youtube-transcript": "^1.2.1", + "youtubei.js": "^5.8.0", + "ytdl-core": "^4.11.5", + "zod": "^3.22.4", + "zod-to-json-schema": "^3.23.0", + "zx": "^7.2.3" + } +} diff --git a/tools/actions.ts b/tools/actions.ts new file mode 100644 index 0000000..470e085 --- /dev/null +++ b/tools/actions.ts @@ -0,0 +1,714 @@ +// actions.ts +import YAML from "yaml"; +import { z } from "zod"; +import { v4 as uuidv4 } from "uuid"; +import { Message } from "../interfaces/message"; +import { eventManager } from "../interfaces/events"; +import fs from "fs/promises"; +import path from "path"; +import { discordAdapter } from "../interfaces"; +import { RunnableToolFunctionWithParse } from "openai/lib/RunnableFunction.mjs"; +import { getTools, zodFunction } from "."; +import { ask } from "./ask"; +import Fuse from "fuse.js"; +import cron from "node-cron"; +import { pathInDataDir, userConfigs } from "../config"; +import { get_event_listeners } from "./events"; +import { memory_manager_guide, memory_manager_init } from "./memory-manager"; + +// Paths to the JSON files +const ACTIONS_FILE_PATH = pathInDataDir("actions.json"); + +// Define schema for creating an action +export const CreateActionParams = z.object({ + actionId: z + .string() + .describe( + "The unique identifier for the action. Make this relevant to the action." + ), + description: z + .string() + .min(1, "description is required") + .describe("Short description of the action."), + schedule: z + .object({ + type: z.enum(["delay", "cron"]).describe("Type of scheduling."), + time: z.union([ + z.number().positive().int().describe("Delay in seconds."), + z.string().describe("Cron expression."), + ]), + }) + .describe("Scheduling details for the action."), + instruction: z + .string() + .min(1, "instruction is required") + .describe( + "Detailed instructions on what to do when the action is executed." + ), + tool_names: z + .array(z.string()) + .optional() + .describe( + `Names of the tools required to execute the instruction of an action. + Each of these should look something like "home_assistant_manager" or "calculator" and NOT "function:home_assistant_manager" or "function.calculator".` + ), + notify: z + .boolean() + .describe( + "Wheater to notify the user when the action is executed or not with the action's output." + ), +}); + +// Type for creating an action +export type CreateActionParams = z.infer; + +// Define schema for searching actions +export const SearchActionsParams = z.object({ + userId: z.string().optional(), + actionId: z.string().optional(), +}); + +// Type for searching actions +export type SearchActionsParams = z.infer; + +// Define schema for removing an action +const RemoveActionParamsSchema = z.object({ + actionId: z.string().min(1, "actionId is required"), +}); + +// Type for removing an action +type RemoveActionParams = z.infer; + +// Define schema for updating an action +export const UpdateActionParams = z + .object({ + actionId: z.string().min(1, "actionId is required"), + description: z.string().min(1, "description is required"), + schedule: z + .object({ + type: z.enum(["delay", "cron"]).describe("Type of scheduling."), + time: z.union([ + z.number().positive().int().describe("Delay in seconds."), + z.string().describe("Cron expression."), + ]), + }) + .describe("Scheduling details for the action."), + instruction: z + .string() + .min(1, "instruction is required") + .describe( + "Detailed instructions on what to do when the action is executed." + ) + .optional(), + template: z + .string() + .min(1, "template is required") + .describe( + "A string template to format the action payload. Use double curly braces to reference variables, e.g., {{variableName}}." + ) + .optional(), + tool_names: z + .array(z.string()) + .optional() + .describe( + "Names of the tools required to execute the instruction when the action is executed." + ), + notify: z + .boolean() + .optional() + .describe( + "Whether to notify the user when the action is executed or not with the action's output." + ), + }) + .refine( + (data) => { + const hasInstruction = !!data.instruction; + const hasTemplate = !!data.template; + return hasInstruction !== hasTemplate; // Either instruction or template must be present, but not both + }, + { + message: + "Either 'instruction' with 'tool_names' or 'template' must be provided, but not both.", + } + ); + +// Type for updating an action +export type UpdateActionParams = z.infer; + +// Define the structure of an Action +interface Action { + actionId: string; + description: string; + userId: string; + schedule: { + type: "delay" | "cron"; + time: number | string; + }; + instruction?: string; + template?: string; + tool_names?: string[]; + notify: boolean; + created_at: string; // ISO string for serialization +} + +// In-memory storage for actions +const actionsMap: Map = new Map(); + +// Helper function to load actions from the JSON file +async function loadActionsFromFile() { + try { + const data = await fs.readFile(ACTIONS_FILE_PATH, "utf-8"); + const parsed = JSON.parse(data) as Action[]; + parsed.forEach((action) => { + actionsMap.set(action.actionId, action); + scheduleAction(action); + }); + console.log( + `✅ Loaded ${actionsMap.size} actions from ${ACTIONS_FILE_PATH}` + ); + } catch (error: any) { + if (error.code === "ENOENT") { + // File does not exist, create an empty file + await saveActionsToFile(); + console.log(`📄 Created new actions file at ${ACTIONS_FILE_PATH}`); + } else { + console.error(`❌ Failed to load actions from file: ${error.message}`); + } + } +} + +// Helper function to save actions to the JSON file +async function saveActionsToFile() { + const data = JSON.stringify(Array.from(actionsMap.values()), null, 2); + await fs.writeFile(ACTIONS_FILE_PATH, data, "utf-8"); +} + +// Function to schedule an action based on its schedule +function scheduleAction(action: Action) { + if ( + action.schedule.type === "delay" && + typeof action.schedule.time === "number" + ) { + const createdAt = new Date(action.created_at).getTime(); + const currentTime = Date.now(); + const delayInMs = action.schedule.time * 1000; + const elapsedTime = currentTime - createdAt; + const remainingTime = delayInMs - elapsedTime; + + if (remainingTime > 0) { + setTimeout(async () => { + await executeAction(action); + // After execution, remove the action as it's a one-time delay + actionsMap.delete(action.actionId); + await saveActionsToFile(); + console.log(`🗑️ Removed action "${action.actionId}" after execution.`); + }, remainingTime); + console.log( + `⏰ Scheduled action "${action.actionId}" to run in ${Math.round( + remainingTime / 1000 + )} seconds.` + ); + } else { + // If the remaining time is less than or equal to zero, execute immediately + executeAction(action).then(async () => { + actionsMap.delete(action.actionId); + await saveActionsToFile(); + console.log( + `🗑️ Removed action "${action.actionId}" after immediate execution.` + ); + }); + console.log( + `⚡ Executed action "${action.actionId}" immediately as the delay has already passed.` + ); + } + } else if ( + action.schedule.type === "cron" && + typeof action.schedule.time === "string" + ) { + // Schedule the action using the cron expression + cron.schedule(action.schedule.time, () => { + executeAction(action); + }); + + console.log( + `🕒 Scheduled action "${action.actionId}" with cron expression "${action.schedule.time}".` + ); + } else { + console.error(`❌ Invalid schedule for action "${action.actionId}".`); + } +} + +// Function to execute an action +async function executeAction(action: Action) { + try { + // Recreate the Message instance using discordAdapter + const contextMessage: Message = await discordAdapter.createMessageInterface( + action.userId + ); + if (!contextMessage) { + console.error( + `❌ Unable to create Message interface for user "${action.userId}".` + ); + return; + } + + if (action.template) { + // Handle static action with template + const payload = {}; // Define how to obtain payload if needed + const formattedMessage = renderTemplate(action.template, payload); + await contextMessage.send({ content: formattedMessage }); + } else if (action.instruction && action.tool_names) { + // Handle dynamic action with instruction and tools + let tools = getTools( + contextMessage.author.username, + contextMessage + ).filter( + (tool) => + tool.function.name && action.tool_names?.includes(tool.function.name) + ) as RunnableToolFunctionWithParse[] | undefined; + + tools = tools?.length ? tools : undefined; + + const response = await ask({ + model: "gpt-4o-mini", + prompt: `You are an Action Executor. + + You are called to execute an action based on the provided instruction. + + **Guidelines:** + + 1. **Notifying the Current User:** + - Any message you reply with will automatically be sent to the user as a notification. + + **Example:** + + - **Instruction:** "Tell Pooja happy birthday" + - **Tool Names:** ["communication_manager"] + - **Notify:** true + - **Steps:** + 1. Ask \`communication_manager\` to wish Pooja a happy birthday to send a message to the recipient mentioned by the user. + 2. Reply to the current user with "I wished Pooja a happy birthday." to notify the user. + + **Action Details:** + + - **Action ID:** ${action.actionId} + - **Description:** ${action.description} + - **Instruction:** ${action.instruction} + + Use the required tools/managers as needed. + `, + tools: tools?.length ? tools : undefined, + }); + + const content = response.choices[0].message.content ?? undefined; + + // Send a message to the user indicating the action was executed + await contextMessage.send({ content }); + } else { + console.error( + `❌ Action "${action.actionId}" has neither 'instruction' nor 'template' defined properly.` + ); + } + } catch (error) { + console.error(`Error executing action "${action.actionId}":`, error); + } +} + +/** + * Simple template renderer that replaces {{key}} with corresponding values from payload. + * @param template - The string template containing placeholders like {{key}}. + * @param payload - The payload containing key-value pairs. + * @returns The formatted string with placeholders replaced by payload values. + */ +function renderTemplate( + template: string, + payload: Record +): string { + return template.replace(/{{\s*([^}]+)\s*}}/g, (_, key) => { + return payload[key.trim()] || `{{${key.trim()}}}`; + }); +} + +/** + * Creates an action. + * @param params - Parameters for creating the action. + * @param contextMessage - The message context from which the action is created. + * @returns A JSON object containing the action details and a success message, or an error. + */ +export async function create_action( + params: CreateActionParams, + contextMessage: Message +): Promise { + const parsed = CreateActionParams.safeParse(params); + if (!parsed.success) { + return { error: parsed.error.errors }; + } + + let { actionId, description, schedule, instruction, tool_names } = + parsed.data; + + // Get the userId from contextMessage + const userId: string = contextMessage.author.id; + + if (actionsMap.has(actionId)) { + return { error: `❌ Action with ID "${actionId}" already exists.` }; + } + + const send_message_tools = tool_names?.filter( + (t) => t.includes("send_message") && !t.startsWith("confirm_") + ); + if (send_message_tools?.length) { + return { + confirmation: `You are using tools that sends a message to the user explicitly. + Tool names that triggered this confirmation: [${send_message_tools.join( + ", " + )}] + Use these only to send a message to a different user or channel. Not sending this tool would by default send the message to the user anyway. + To use this tool anyway like to send a message to a different user or channel, please re run create command and prefix the tool name with 'confirm_'`, + }; + } + + tool_names = tool_names?.map((t) => + t.startsWith("confirm_") ? t.replace("confirm_", "") : t + ); + + const action: Action = { + actionId, + description, + userId, + schedule, + instruction, + tool_names, + notify: params.notify ?? true, + created_at: new Date().toISOString(), + }; + + actionsMap.set(actionId, action); + await saveActionsToFile(); + + // Schedule the action + scheduleAction(action); + + return { + actionId, + description, + userId, + schedule, + instruction, + tool_names, + created_at: action.created_at, + message: "✅ Action created and scheduled successfully.", + }; +} + +// 1. Define schema for getting actions +export const GetActionsParams = z.object({}); + +export type GetActionsParams = z.infer; + +// 2. Implement the get_actions function +export async function get_actions( + params: GetActionsParams, + contextMessage: Message +): Promise { + // Get the userId from contextMessage + const userId: string = contextMessage.author.id; + + // Get all actions created by this user + const userActions = Array.from(actionsMap.values()).filter( + (action) => action.userId === userId + ); + + return { + actions: userActions, + }; +} + +/** + * Removes an action by its actionId by fully deleting it. + * @param params - Parameters containing the actionId. + * @returns A JSON object confirming removal or an error. + */ +export async function remove_action(params: RemoveActionParams): Promise { + // Validate parameters using zod + const parsed = RemoveActionParamsSchema.safeParse(params); + if (!parsed.success) { + return { error: parsed.error.errors }; + } + + const { actionId } = parsed.data; + + const action = actionsMap.get(actionId); + + if (!action) { + return { + error: `❌ Action with ID "${actionId}" not found.`, + }; + } + + // Remove the action from the map + actionsMap.delete(actionId); + await saveActionsToFile(); + + // Note: In a real implementation, you'd also need to cancel the scheduled task. + // This can be managed by keeping track of timers or using a scheduler that supports cancellation. + + return { + message: `✅ Action with ID "${actionId}" removed successfully.`, + }; +} + +/** + * Updates the details of an action. + * @param params - Parameters containing the actionId and fields to update. + * @param contextMessage - The message context to identify the user. + * @returns A JSON object confirming the update or an error. + */ +export async function update_action( + params: UpdateActionParams, + contextMessage: Message +): Promise { + // Validate parameters using zod + const parsed = UpdateActionParams.safeParse(params); + if (!parsed.success) { + return { error: parsed.error.errors }; + } + + const { + actionId, + description, + schedule, + instruction, + template, + tool_names, + notify, + } = parsed.data; + + // Get the userId from contextMessage + const userId: string = contextMessage.author.id; + + // Find the action + const action = actionsMap.get(actionId); + if (!action) { + return { error: `❌ Action with ID "${actionId}" not found.` }; + } + + // Ensure the action belongs to the user + if (action.userId !== userId) { + return { error: `❌ You do not have permission to update this action.` }; + } + + // Update fields + action.description = description; + action.schedule = schedule; + action.instruction = instruction; + action.template = template; + action.notify = notify ?? action.notify; + action.tool_names = tool_names; + + actionsMap.set(actionId, action); + await saveActionsToFile(); + + // Reschedule the action + scheduleAction(action); + + return { + actionId, + description, + userId, + schedule, + instruction, + template, + tool_names, + created_at: action.created_at, + message: "✅ Action updated and rescheduled successfully.", + }; +} + +const action_tools: ( + context_message: Message +) => RunnableToolFunctionWithParse[] = (context_message) => [ + zodFunction({ + name: "create_action", + function: (args) => create_action(args, context_message), + schema: CreateActionParams, + description: `Creates a new action. + +**Example:** +- **User:** "Send a summary email in 10 minutes" + - **Action ID:** "send_summary_email" + - **Description:** "Sends a summary email after a delay." + - **Schedule:** { type: "delay", time: 600 } + - **Instruction:** "Compose and send a summary email to the user." + - **Required Tools:** ["email_service"] + +**Notes:** +- Supported scheduling types: 'delay' (in seconds), 'cron' (cron expressions). +`, + }), + // zodFunction({ + // name: "get_actions", + // function: (args) => get_actions(args, context_message), + // schema: GetActionsParams, + // description: `Retrieves all actions created by the user. + + // Use this to obtain action IDs for updating or removing actions." + // `, + // }), + zodFunction({ + name: "update_action", + function: (args) => update_action(args, context_message), + schema: UpdateActionParams, + description: `Updates an existing action's details. + +Provide all details of the action to replace it with the new parameters. +`, + }), + zodFunction({ + name: "remove_action", + function: (args) => remove_action(args), + schema: RemoveActionParamsSchema, + description: `Removes an action using the action ID.`, + }), +]; + +export const ActionManagerParamsSchema = z.object({ + request: z + .string() + .describe( + "What the user wants you to do in the action. Please provide the time / schedule as well." + ), + tool_names: z + .array(z.string()) + .optional() + .describe("Names of the tools required to execute the instruction."), + suggested_time_to_run_action: z.string().optional(), +}); + +export type ActionManagerParams = z.infer; + +// -------------------- Fuzzy Search for Actions -------------------- // + +export const FuzzySearchActionsParams = z.object({ + query: z.string(), +}); +export type FuzzySearchActionsParams = z.infer; + +export async function fuzzySearchActions({ + query, +}: FuzzySearchActionsParams): Promise<{ matches: any[] }> { + try { + // Fetch all actions (Assuming get_actions is already defined and returns actions) + const { actions } = await get_actions({}, { + author: { id: "system" }, + } as any); // Replace with actual contextMessage if available + + if (!actions) { + return { matches: [] }; + } + + const fuseOptions = { + keys: ["description", "actionId"], + threshold: 0.3, // Adjust the threshold as needed + }; + + const fuse = new Fuse(actions, fuseOptions); + const results = fuse.search(query); + + // Get top 2 results + const topMatches = results.slice(0, 2).map((result) => result.item); + + return { matches: topMatches }; + } catch (error) { + console.error("Error performing fuzzy search on actions:", error); + return { matches: [] }; + } +} + +// -------------------- Manager Function -------------------- // + +/** + * Manages user requests related to actions by orchestrating CRUD operations. + * It can handle creating, updating, retrieving, and removing actions based on user input. + * + * @param params - Parameters containing the user's request, the action name, and an optional delay. + * @returns A JSON object containing the response from executing the action or an error. + */ +export async function actionManager( + { request, tool_names, suggested_time_to_run_action }: ActionManagerParams, + context_message: Message +): Promise { + // Validate parameters using Zod + const parsed = ActionManagerParamsSchema.safeParse({ + request, + }); + if (!parsed.success) { + return { error: parsed.error.errors }; + } + + const { request: userRequest } = parsed.data; + + const all_actions = await get_actions({}, context_message); + + const userConfigData = userConfigs.find((config) => + config.identities.find((id) => id.id === context_message.author.id) + ); + + // Construct the prompt for the ask function + const prompt = `You are an Action Manager. + +Your role is to manage scheduled actions. + +**Current Time:** ${new Date().toLocaleString()} + +---- + +${memory_manager_guide("actions_manager")} + +---- + +**Actions You Have Set Up for This User:** +${JSON.stringify(all_actions.actions)} + +**Current User Details:** +${JSON.stringify(userConfigData)} + +**Tools Suggested by user for Action:** +${JSON.stringify(tool_names)} + +--- + +Use the data provided above to fulfill the user's request. +`; + + const tools = action_tools(context_message).concat( + memory_manager_init(context_message, "actions_manager") + ); + + // console.log("Action Manager Tools:", tools); + + // Execute the action using the ask function with the appropriate tools + try { + const response = await ask({ + prompt, + message: `${userRequest} + + Suggested time: ${suggested_time_to_run_action} + `, + seed: `action_manager_${context_message.channelId}`, + tools, + }); + + return { + response: response.choices[0].message.content, + }; + } catch (error) { + console.error("Error executing action via manager:", error); + return { + error: "❌ An error occurred while executing your request.", + }; + } +} + +// Initialize by loading actions from file when the module is loaded +loadActionsFromFile(); diff --git a/tools/ask.ts b/tools/ask.ts new file mode 100644 index 0000000..cbd5316 --- /dev/null +++ b/tools/ask.ts @@ -0,0 +1,394 @@ +import OpenAI from "openai"; +import { saveApiUsage } from "../usage"; +import axios from "axios"; +import fs from "fs"; +import { RunnableToolFunctionWithParse } from "openai/lib/RunnableFunction.mjs"; +import { + ChatCompletion, + ChatCompletionAssistantMessageParam, + ChatCompletionMessageParam, +} from "openai/resources/index.mjs"; +import { send_sys_log } from "../interfaces/log"; +import { pathInDataDir } from "../config"; + +const ai_token = process.env.OPENAI_API_KEY?.trim(); +const groq_token = process.env.GROQ_API_KEY?.trim(); +const groq_baseurl = process.env.GROQ_BASE_URL?.trim(); + +// Messages saving implementation + +interface MessageHistory { + messages: ChatCompletionMessageParam[]; + timeout: NodeJS.Timer; +} + +const seedMessageHistories: Map = new Map(); +const HISTORY_TIMEOUT_MS = 10 * 60 * 1000; + +/** + * Retrieves the message history for a given seed. + * If it doesn't exist, initializes a new history. + * Resets the timeout each time it's accessed. + * + * @param seed - The seed identifier for the message history + * @returns The message history array + */ +function getMessageHistory(seed: string): ChatCompletionMessageParam[] { + const existingHistory = seedMessageHistories.get(seed); + + if (existingHistory) { + // Reset the timeout + clearTimeout(existingHistory.timeout); + existingHistory.timeout = setTimeout(() => { + seedMessageHistories.delete(seed); + console.log(`Cleared message history for seed: ${seed}`); + send_sys_log(`Cleared message history for seed: ${seed}`); + }, HISTORY_TIMEOUT_MS); + + return existingHistory.messages; + } else { + // Initialize new message history + const messages: ChatCompletionMessageParam[] = []; + const timeout = setTimeout(() => { + seedMessageHistories.delete(seed); + console.log(`Cleared message history for seed: ${seed}`); + send_sys_log(`Cleared message history for seed: ${seed}`); + }, HISTORY_TIMEOUT_MS); + + seedMessageHistories.set(seed, { messages, timeout }); + return messages; + } +} + +/** + * Sets the entire message history for a given seed. + * + * @param seed - The seed identifier for the message history + * @param messages - The complete message history to set + */ +function setMessageHistory( + seed: string, + messages: ChatCompletionMessageParam[] +): void { + const existingHistory = seedMessageHistories.get(seed); + if (existingHistory) { + clearTimeout(existingHistory.timeout); + existingHistory.messages = messages; + existingHistory.timeout = setTimeout(() => { + seedMessageHistories.delete(seed); + console.log(`Cleared message history for seed: ${seed}`); + send_sys_log(`Cleared message history for seed: ${seed}`); + }, HISTORY_TIMEOUT_MS); + } else { + const timeout = setTimeout(() => { + seedMessageHistories.delete(seed); + console.log(`Cleared message history for seed: ${seed}`); + send_sys_log(`Cleared message history for seed: ${seed}`); + }, HISTORY_TIMEOUT_MS); + seedMessageHistories.set(seed, { messages, timeout }); + } +} + +/** + * Appends a message to the message history for a given seed. + * + * @param seed - The seed identifier for the message history + * @param message - The message to append + */ +function appendMessage( + seed: string, + message: ChatCompletionMessageParam +): void { + console.log( + "Appending message", + message.content, + "tool_calls" in message && message.tool_calls + ); + + const history = seedMessageHistories.get(seed); + if (history) { + history.messages.push(message); + // Reset the timeout + clearTimeout(history.timeout); + history.timeout = setTimeout(() => { + seedMessageHistories.delete(seed); + send_sys_log(`Cleared message history for seed: ${seed}`); + console.log(`Cleared message history for seed: ${seed}`); + }, HISTORY_TIMEOUT_MS); + } +} + +/** + * The updated ask function with support for persistent message history via a seed. + * Separates system prompt and user message to prevent duplication. + * + * @param params - The parameters for the ask function + * @returns The response from the LLM API + */ +export async function ask({ + model = "gpt-4o-mini", + prompt, // System prompt + message, // User input message (optional) + name, + tools, + seed, +}: { + model?: string; + prompt: string; + message?: string; + name?: string; + tools?: RunnableToolFunctionWithParse[]; + seed?: string; +}): Promise { + // Initialize OpenAI instances + const openai = new OpenAI({ + apiKey: ai_token, + }); + + const groq = new OpenAI({ + apiKey: groq_token, + baseURL: groq_baseurl, + }); + + // Initialize messages array with the system prompt + let messages: ChatCompletionMessageParam[] = [ + { + role: "system", + content: prompt, + }, + ]; + + if (seed && message) { + // Retrieve existing message history + const history = getMessageHistory(seed); + + // Combine system prompt with message history and new user message + messages = [ + { + role: "system", + content: prompt, + }, + ...history, + { + role: "user", + content: message, + name, + }, + ]; + } else if (seed && !message) { + // If seed is provided but no new message, just retrieve history + const history = getMessageHistory(seed); + messages = [ + { + role: "system", + content: prompt, + }, + ...history, + ]; + } else if (!seed && message) { + // If no seed but message is provided, send system prompt and user message without history + messages.push({ + role: "user", + content: message, + name, + }); + } + + let res: ChatCompletion; + + if (model === "groq-small") { + res = await groq.chat.completions.create({ + model: "llama-3.1-8b-instant", + messages, + }); + + if (res.usage) { + saveApiUsage( + new Date().toISOString().split("T")[0], + model, + res.usage.prompt_tokens, + res.usage.completion_tokens + ); + } else { + console.log("No usage data"); + } + + // Handle response with seed + if (seed && res.choices && res.choices.length > 0) { + appendMessage(seed, res.choices[0].message); + } + + return res; + } + + if (tools?.length) { + // Create a new runner with the current messages and tools + const runner = openai.beta.chat.completions + .runTools({ + model, + messages, + tools, + }) + .on("functionCall", (functionCall) => { + send_sys_log(`ASK Function call: ${JSON.stringify(functionCall)}`); + console.log("ASK Function call:", functionCall); + }) + .on("message", (message) => { + // remove empty tool_calls array + if ( + "tool_calls" in message && + message.tool_calls && + message.tool_calls.length === 0 + ) { + message.tool_calls = undefined; + delete message.tool_calls; + } + seed && appendMessage(seed, message); + }) + .on("totalUsage", (usage) => { + send_sys_log( + `ASK Total usage: ${usage.prompt_tokens} prompt tokens, ${usage.completion_tokens} completion tokens` + ); + console.log("ASK Total usage:", usage); + saveApiUsage( + new Date().toISOString().split("T")[0], + model, + usage.prompt_tokens, + usage.completion_tokens + ); + }); + + // Await the final chat completion + res = await runner.finalChatCompletion(); + + return res; + } + + // Default behavior without tools + res = await openai.chat.completions.create({ + model, + messages, + }); + + if (res.usage) { + saveApiUsage( + new Date().toISOString().split("T")[0], + model, + res.usage.prompt_tokens, + res.usage.completion_tokens + ); + } else { + console.log("No usage data"); + } + + // Handle response with seed + if (seed && res.choices && res.choices.length > 0) { + const assistantMessage = res.choices[0].message; + appendMessage(seed, assistantMessage); + } + + return res; +} + +const transcriptionCacheFile = pathInDataDir("transcription_cache.json"); + +export async function get_transcription( + file_url: string, + binary?: boolean, + key?: string +) { + const openai = new OpenAI({ + apiKey: ai_token, + }); + + // Step 1: Check if the transcription for this file URL is already cached + let transcriptionCache: Record = {}; + + // Try to read the cache file if it exists + if (fs.existsSync(transcriptionCacheFile)) { + const cacheData = fs.readFileSync(transcriptionCacheFile, "utf-8"); + transcriptionCache = JSON.parse(cacheData); + } + + if (binary) { + // If transcription for this file_url is already in the cache, return it + if (key && transcriptionCache[key]) { + console.log("Transcription found in cache:", transcriptionCache[key]); + return transcriptionCache[key]; + } + + const binaryData = Buffer.from(file_url, "base64"); + // fs.writeFile("/home/audio_whats.ogg", binaryData, function (err) {}); + + const filePath = `/tmp/audio${Date.now()}.ogg`; + + fs.writeFileSync(filePath, new Uint8Array(binaryData)); + + // Step 3: Send the file to OpenAI's Whisper model + const transcription = await openai.audio.transcriptions.create({ + model: "whisper-1", + file: fs.createReadStream(filePath), + }); + + // Delete the temp file + fs.unlinkSync(filePath); + + // Step 4: Save the transcription to the cache + key && (transcriptionCache[key] = transcription.text); + fs.writeFileSync( + transcriptionCacheFile, + JSON.stringify(transcriptionCache, null, 2) + ); + + console.log("Transcription:", transcription); + + return transcription.text; + } + + // If transcription for this file_url is already in the cache, return it + if (transcriptionCache[file_url]) { + console.log("Transcription found in cache:", transcriptionCache[file_url]); + return transcriptionCache[file_url]; + } + + try { + // Step 2: Download the file from the URL + const response = await axios({ + url: file_url, + method: "GET", + responseType: "stream", + }); + + const filePath = `/tmp/audio${Date.now()}.ogg`; + + // Save the downloaded file locally + const writer = fs.createWriteStream(filePath); + response.data.pipe(writer); + + await new Promise((resolve, reject) => { + writer.on("finish", resolve); + writer.on("error", reject); + }); + + // Step 3: Send the file to OpenAI's Whisper model + const transcription = await openai.audio.transcriptions.create({ + model: "whisper-1", + file: fs.createReadStream(filePath), + }); + + // Delete the temp file + fs.unlinkSync(filePath); + + // Step 4: Save the transcription to the cache + transcriptionCache[file_url] = transcription.text; + fs.writeFileSync( + transcriptionCacheFile, + JSON.stringify(transcriptionCache, null, 2) + ); + + console.log("Transcription:", transcription); + return transcription.text; + } catch (error) { + console.error("Error transcribing audio:", error); + } +} diff --git a/tools/calender.ts b/tools/calender.ts new file mode 100644 index 0000000..113f5a9 --- /dev/null +++ b/tools/calender.ts @@ -0,0 +1,556 @@ +import axios, { AxiosError } from "axios"; +import { z } from "zod"; +import { zodFunction } from "."; +import { RunnableToolFunction } from "openai/lib/RunnableFunction.mjs"; +import { ask } from "./ask"; +import { Message } from "../interfaces/message"; +import { memory_manager_guide, memory_manager_init } from "./memory-manager"; + +const NEXTCLOUD_API_ENDPOINT = + "http://192.168.29.85/remote.php/dav/calendars/raj/"; +const NEXTCLOUD_USERNAME = process.env.NEXTCLOUD_USERNAME; +const NEXTCLOUD_PASSWORD = process.env.NEXTCLOUD_PASSWORD; + +if (!NEXTCLOUD_USERNAME || !NEXTCLOUD_PASSWORD) { + throw new Error( + "Please provide NEXTCLOUD_USERNAME and NEXTCLOUD_PASSWORD environment variables." + ); +} + +const CALENDAR_NAME = "anya"; // Primary read-write calendar +const READ_ONLY_CALENDARS = ["google"]; // Read-only calendar + +const apiClient = axios.create({ + baseURL: NEXTCLOUD_API_ENDPOINT, + auth: { + username: NEXTCLOUD_USERNAME, + password: NEXTCLOUD_PASSWORD, + }, + headers: { + "Content-Type": "application/xml", // Ensure correct content type for DAV requests + }, +}); + +// Schemas for each function's parameters +export const EventParams = z.object({ + event_id: z.string().describe("The unique ID of the event."), + calendar: z + .string() + .optional() + .describe("The calendar the event belongs to."), +}); +export type EventParams = z.infer; + +export const CreateEventParams = z.object({ + summary: z.string().describe("The summary (title) of the event."), + description: z.string().optional().describe("The description of the event."), + start_time: z + .string() + .describe("The start time of the event in ISO 8601 format."), + end_time: z + .string() + .describe("The end time of the event in ISO 8601 format."), + location: z.string().optional().describe("The location of the event."), + attendees: z + .array(z.string()) + .optional() + .describe("List of attendee email addresses."), + all_day: z + .boolean() + .optional() + .describe("Whether the event is an all-day event."), + recurrence: z + .string() + .optional() + .describe("The recurrence rule for the event in RRULE format."), +}); +export type CreateEventParams = z.infer; + +export const UpdateEventParams = z.object({ + event_id: z.string().describe("The unique ID of the event to update."), + summary: z.string().optional().describe("The updated summary of the event."), + description: z + .string() + .optional() + .describe("The updated description of the event."), + start_time: z + .string() + .optional() + .describe("The updated start time in ISO 8601 format."), + end_time: z + .string() + .optional() + .describe("The updated end time in ISO 8601 format."), + location: z + .string() + .optional() + .describe("The updated location of the event."), + attendees: z + .array(z.string()) + .optional() + .describe("Updated list of attendee email addresses."), + calendar: z + .string() + .optional() + .describe("The calendar the event belongs to."), + all_day: z + .boolean() + .optional() + .describe("Whether the event is an all-day event."), + recurrence: z + .string() + .optional() + .describe("The updated recurrence rule for the event in RRULE format."), +}); +export type UpdateEventParams = z.infer; + +function validateRecurrenceRule(recurrence: string): boolean { + const rrulePattern = + /^RRULE:(FREQ=(DAILY|WEEKLY|MONTHLY|YEARLY);?(\w+=\w+;?)*)$/; + return rrulePattern.test(recurrence); +} + +// Functions +export async function createEvent({ + summary, + description, + start_time, + end_time, + location, + attendees, + all_day, + recurrence, +}: CreateEventParams) { + const formatTime = (dateTime: string, allDay: boolean | undefined) => { + if (allDay) { + const date = new Date(dateTime); + return `${date.getUTCFullYear()}${(date.getUTCMonth() + 1) + .toString() + .padStart(2, "0")}${date.getUTCDate().toString().padStart(2, "0")}`; + } else { + return formatDateTime(dateTime); + } + }; + + if (recurrence && !validateRecurrenceRule(recurrence)) { + return { error: "Invalid recurrence rule syntax." }; + } + + // Ensure DTEND for all-day events is correctly handled (should be the next day) + const dtend = all_day + ? formatTime(end_time || start_time, all_day) + : formatTime(end_time, all_day); + + const icsContent = [ + "BEGIN:VCALENDAR", + "VERSION:2.0", + "PRODID:-//xrehpicx//anya//EN", + "BEGIN:VEVENT", + `UID:${Date.now()}@cloud.raj.how`, + `SUMMARY:${summary}`, + `DESCRIPTION:${description || ""}`, + `DTSTART${all_day ? ";VALUE=DATE" : ""}:${formatTime(start_time, all_day)}`, + `DTEND${all_day ? ";VALUE=DATE" : ""}:${dtend}`, + `LOCATION:${location || ""}`, + attendees + ? attendees + .map((email) => `ATTENDEE;CN=${email}:mailto:${email}`) + .join("\r\n") + : "", + recurrence || "", + "END:VEVENT", + "END:VCALENDAR", + ] + .filter(Boolean) + .join("\r\n"); + + try { + const response = await apiClient.put( + `${CALENDAR_NAME}/${Date.now()}.ics`, + icsContent + ); + return { response: "Event created successfully" }; + } catch (error) { + console.log("Failed to create event:", error); + console.log((error as AxiosError).response?.data); + return { + error: `Error: ${error}\n${(error as AxiosError).response?.data}`, + }; + } +} + +export async function updateEvent({ + event_id, + summary, + description, + start_time, + end_time, + location, + attendees, + calendar = CALENDAR_NAME, + all_day, + recurrence, +}: UpdateEventParams) { + if (READ_ONLY_CALENDARS.includes(calendar)) { + return { error: "This event is read-only and cannot be updated." }; + } + + // Fetch the existing event to ensure we have all required data + const existingEvent = await getEvent({ event_id, calendar }); + + if (existingEvent.error) { + return { error: "Event not found" }; + } + + // Determine whether the event is all-day, and format times accordingly + const isAllDay = all_day !== undefined ? all_day : existingEvent.all_day; + const formatTime = ( + dateTime: string | undefined, + allDay: boolean + ): string => { + if (!dateTime) return ""; + if (allDay) { + const date = new Date(dateTime); + return `${date.getUTCFullYear()}${(date.getUTCMonth() + 1) + .toString() + .padStart(2, "0")}${date.getUTCDate().toString().padStart(2, "0")}`; + } else { + return formatDateTime(dateTime); + } + }; + + if (recurrence && !validateRecurrenceRule(recurrence)) { + return { error: "Invalid recurrence rule syntax." }; + } + + // Format the ICS content, ensuring that all required fields are present + const updatedICSContent = [ + "BEGIN:VCALENDAR", + "VERSION:2.0", + "PRODID:-//xrehpicx//anya//EN", + "BEGIN:VEVENT", + `UID:${event_id}`, + `SUMMARY:${summary || existingEvent.summary}`, + `DESCRIPTION:${description || existingEvent.description}`, + `DTSTART${isAllDay ? ";VALUE=DATE" : ""}:${formatTime( + start_time || existingEvent.start_time, + isAllDay + )}`, + `DTEND${isAllDay ? ";VALUE=DATE" : ""}:${formatTime( + end_time || existingEvent.end_time, + isAllDay + )}`, + `LOCATION:${location || existingEvent.location}`, + attendees + ? attendees + .map((email) => `ATTENDEE;CN=${email}:mailto:${email}`) + .join("\r\n") + : existingEvent.attendees, + recurrence || existingEvent.recurrence, + "END:VEVENT", + "END:VCALENDAR", + ] + .filter(Boolean) + .join("\r\n"); + + try { + const response = await apiClient.put( + `${calendar}/${event_id}.ics`, + updatedICSContent + ); + + return { response: "Event updated successfully" }; + } catch (error) { + console.log("Failed to update event:", error); + console.log((error as AxiosError).response?.data); + return { + error: `Error: ${error}\n${(error as AxiosError).response?.data}`, + }; + } +} + +export async function deleteEvent({ event_id }: EventParams) { + try { + const deleteUrl = `${NEXTCLOUD_API_ENDPOINT}${CALENDAR_NAME}/${event_id}.ics`; // Correctly form the URL + console.log(`Attempting to delete event at: ${deleteUrl}`); + + const response = await apiClient.delete(deleteUrl); + console.log("Event deleted successfully:", response.status); + return { response: "Event deleted successfully" }; + } catch (error) { + console.log( + "Failed to delete event:", + (error as AxiosError).response?.data || (error as AxiosError).message + ); + return { + error: `Error: ${ + (error as AxiosError).response?.data || (error as AxiosError).message + }`, + }; + } +} + +export async function getEvent({ + event_id, + calendar = CALENDAR_NAME, +}: EventParams) { + try { + const response = await apiClient.get(`${calendar}/${event_id}.ics`); + const eventData = response.data; + const isReadOnly = READ_ONLY_CALENDARS.includes(calendar); + + return { + ...eventData, + read_only: isReadOnly ? "Read-Only" : "Editable", + }; + } catch (error) { + console.log(error); + return { + error: `Error: ${error}\n${(error as AxiosError).response?.data}`, + }; + } +} + +export async function listEvents({ + start_time, + end_time, +}: { + start_time: string; + end_time: string; +}) { + try { + const startISOTime = convertToISOFormat(start_time); + const endISOTime = convertToISOFormat(end_time); + + const allEvents: any[] = []; + + for (const calendar of [CALENDAR_NAME, ...READ_ONLY_CALENDARS]) { + const calendarUrl = `${NEXTCLOUD_API_ENDPOINT}${calendar}/`; + console.log(`Accessing calendar URL: ${calendarUrl}`); + + try { + const testResponse = await apiClient.get(calendarUrl); + console.log(`Test response for ${calendarUrl}: ${testResponse.status}`); + } catch (testError) { + console.error( + `Error accessing ${calendarUrl}: ${(testError as AxiosError).message}` + ); + continue; + } + + console.log( + `Making REPORT request to ${calendarUrl} for events between ${startISOTime} and ${endISOTime}` + ); + + let reportResponse; + try { + reportResponse = await apiClient.request({ + method: "REPORT", + url: calendarUrl, + headers: { Depth: "1" }, + data: ` + + + + + + + + + + `, + }); + console.log( + `REPORT request successful: Status ${reportResponse.status}` + ); + } catch (reportError) { + console.error( + `REPORT request failed for ${calendarUrl}: ${ + (reportError as AxiosError).response?.data || + (reportError as AxiosError).message + }` + ); + continue; + } + + console.log(`Parsing iCal response for calendar ${calendar}`); + const icsFiles = parseICalResponse(reportResponse.data); + + for (const icsFile of icsFiles) { + const fullIcsUrl = `http://192.168.29.85${icsFile}?export`; + const eventId = icsFile.split("/").pop()?.replace(".ics", ""); + console.log(`Fetching event data from ${fullIcsUrl}`); + + try { + const eventResponse = await apiClient.get(fullIcsUrl, { + responseType: "text", + }); + const eventData = eventResponse.data; + + allEvents.push({ + event_id: eventId, // Add event ID explicitly here + data: eventData, + calendar, + read_only: READ_ONLY_CALENDARS.includes(calendar) + ? "Read-Only" + : "Editable", + }); + console.log(`Event data fetched successfully from ${fullIcsUrl}`); + } catch (eventError) { + console.error( + `Failed to fetch event data from ${fullIcsUrl}: ${ + (eventError as AxiosError).response?.data || + (eventError as AxiosError).message + }` + ); + } + } + } + + return allEvents; + } catch (error) { + console.log( + "Final catch block error:", + (error as AxiosError).response?.data || (error as AxiosError).message + ); + return { + error: `Error: ${ + (error as AxiosError).response?.data || (error as AxiosError).message + }`, + }; + } +} + +// Helper function to convert datetime to ISO format in UTC +function convertToISOFormat(dateTime: string): string { + const date = new Date(dateTime); + return date.toISOString().replace(/[-:]/g, "").split(".")[0] + "Z"; +} + +// Helper function to parse iCal response +function parseICalResponse(response: string): string[] { + const hrefRegex = /([^<]+)<\/d:href>/g; + const matches = []; + let match; + while ((match = hrefRegex.exec(response)) !== null) { + matches.push(match[1]); + } + return matches; +} + +// Helper function to format datetime for iCalendar +function formatDateTime(dateTime: string): string { + const date = new Date(dateTime); + const year = date.getUTCFullYear().toString().padStart(4, "0"); + const month = (date.getUTCMonth() + 1).toString().padStart(2, "0"); + const day = date.getUTCDate().toString().padStart(2, "0"); + const hours = date.getUTCHours().toString().padStart(2, "0"); + const minutes = date.getUTCMinutes().toString().padStart(2, "0"); + const seconds = date.getUTCSeconds().toString().padStart(2, "0"); + return `${year}${month}${day}T${hours}${minutes}${seconds}Z`; // UTC format required by iCalendar +} + +// Integration into runnable tools +export let calendar_tools: RunnableToolFunction[] = [ + zodFunction({ + function: createEvent, + name: "createCalendarEvent", + schema: CreateEventParams, + description: "Create a new event in the 'anya' calendar.", + }), + zodFunction({ + function: updateEvent, + name: "updateCalendarEvent", + schema: UpdateEventParams, + description: + "Update an event in the 'anya' calendar. Cannot update read-only events.", + }), + zodFunction({ + function: deleteEvent, + name: "deleteCalendarEvent", + schema: EventParams, + description: + "Delete an event from the 'anya' calendar. Cannot delete read-only events.", + }), + zodFunction({ + function: getEvent, + name: "getCalendarEvent", + schema: EventParams, + description: + "Retrieve an event from the 'anya' calendar. Indicates if the event is read-only.", + }), + zodFunction({ + function: listEvents, + name: "listCalendarEvents", + schema: z.object({ + start_time: z.string().describe("Start time in ISO 8601 format."), + end_time: z.string().describe("End time in ISO 8601 format."), + }), + description: + "List events within a time range from the 'anya' calendar, including read-only events.", + }), +]; + +export function getCalendarSystemPrompt() { + return `Manage your 'anya' calendar on Nextcloud using these functions to create, update, delete, and list events. + +Read-only events cannot be updated or deleted; they are labeled as "Read-Only" when retrieved or listed. + +Use correct ISO 8601 time formats and handle event IDs carefully. + +**Do not use this for reminders.** + +User's primary emails: r@raj.how and raj@cloud.raj.how + +When creating or updating an event, inform the user of the event date or details updated. +`; +} + +export const CalendarManagerParams = z.object({ + request: z.string().describe("User's request regarding calendar events."), +}); +export type CalendarManagerParams = z.infer; + +export async function calendarManager( + { request }: CalendarManagerParams, + context_message: Message +) { + // Set start and end dates for listing events + const startDate = new Date(); + startDate.setDate(1); + startDate.setMonth(startDate.getMonth() - 1); + const endDate = new Date(); + endDate.setDate(1); + endDate.setMonth(endDate.getMonth() + 2); + + const response = await ask({ + model: "gpt-4o-mini", + prompt: `You are a calendar manager for the 'anya' calendar on Nextcloud. + +Understand the user's request regarding calendar events (create, update, delete, list) and handle it using available tools. + +Use correct ISO 8601 time formats. Provide feedback about actions taken, including event dates or details updated. + +User's primary emails: r@raj.how and raj@cloud.raj.how. Inform the user of the date of any created or updated event. + +---- +${memory_manager_guide("calendar_manager")} +---- + +Current Time: ${new Date().toISOString()} + +Events from ${startDate.toISOString()} to ${endDate.toISOString()}: +${await listEvents({ + start_time: startDate.toISOString(), + end_time: endDate.toISOString(), +})} + `, + tools: calendar_tools.concat( + memory_manager_init(context_message, "calendar_manager") + ) as any, + message: request, + seed: `calendar-manager-${context_message.channelId}`, + }); + + return { response }; +} diff --git a/tools/cat.ts b/tools/cat.ts new file mode 100644 index 0000000..b3a0fef --- /dev/null +++ b/tools/cat.ts @@ -0,0 +1,54 @@ +import { z } from "zod"; + +export const GenerateCatImageUrlParams = z.object({ + tag: z.string().optional(), + text: z.string().optional(), + fontSize: z.number().optional(), + fontColor: z.string().optional(), + gif: z.boolean().optional(), +}); +export type GenerateCatImageUrlParams = z.infer< + typeof GenerateCatImageUrlParams +>; + +export const GenerateCatImageUrlResponse = z.string(); +export type GenerateCatImageUrlResponse = z.infer< + typeof GenerateCatImageUrlResponse +>; + +export async function generate_cat_image_url({ + tag, + text, + fontSize, + fontColor, + gif, +}: GenerateCatImageUrlParams): Promise { + let url = "/cat"; + + if (gif) { + url += "/gif"; + } + + if (tag) { + url += `/${tag}`; + } + + if (text) { + url += `/says/${text}`; + } + + if (fontSize || fontColor) { + if (!text) { + url += `/says/`; // Ensuring 'says' is in the URL for font options + } + url += `${text ? "" : "?"}`; + if (fontSize) { + url += `fontSize=${fontSize}`; + } + if (fontColor) { + url += `${fontSize ? "&" : ""}fontColor=${fontColor}`; + } + } + + return { url }; +} diff --git a/tools/chat-search.ts b/tools/chat-search.ts new file mode 100644 index 0000000..5f299e2 --- /dev/null +++ b/tools/chat-search.ts @@ -0,0 +1,50 @@ +// tools/chat-search.ts + +import { z } from "zod"; +import fuzzysort from "fuzzysort"; +import { Message } from "../interfaces/message"; + +// Define the search parameters schema +export const SearchChatParams = z.object({ + query: z.string(), + k: z.number().max(100).default(5).optional(), + limit: z.number().max(100).default(100).optional(), + user_only: z.boolean().default(false).optional(), +}); +export type SearchChatParams = z.infer; + +// Function to search chat messages +export async function search_chat( + { query, k = 5, limit = 100, user_only = false }: SearchChatParams, + context_message: Message +) { + // Fetch recent messages from the current channel + const messages = await context_message.fetchChannelMessages(limit); + + // Filter messages if user_only is true + const filteredMessages = user_only + ? messages.filter((msg) => msg.author.id === context_message.author.id) + : messages; + + // Prepare list for fuzzysort + const list = filteredMessages.map((msg) => ({ + message: msg, + content: msg.content, + })); + + // Perform fuzzy search on message contents + const results = fuzzysort.go(query, list, { key: "content", limit: k }); + + // Map results back to messages + const matchedMessages = results.map((result) => { + const matchedMessage = result.obj.message; + return { + content: matchedMessage.content, + author: matchedMessage.author.username, + timestamp: matchedMessage.timestamp, + id: matchedMessage.id, + }; + }); + + return { results: matchedMessages }; +} diff --git a/tools/communication.ts b/tools/communication.ts new file mode 100644 index 0000000..4b3ace7 --- /dev/null +++ b/tools/communication.ts @@ -0,0 +1,155 @@ +import { z } from "zod"; +import { zodFunction } from "."; +import { send_message_to, SendMessageParams } from "./messenger"; +import { send_email, ResendParams } from "./resend"; +import { Message } from "../interfaces/message"; +import { search_user, SearchUserParams } from "./search-user"; +import { RunnableToolFunctionWithParse } from "openai/lib/RunnableFunction.mjs"; +import { ask } from "./ask"; +import { memory_manager_guide, memory_manager_init } from "./memory-manager"; +import { userConfigs } from "../config"; + +const CommunicationManagerSchema = z.object({ + request: z.string(), + prefered_platform: z + .string() + .optional() + .describe( + "The platform you prefer to use, you can leave this empty to default to the current user's platform." + ), + prefered_recipient_details: z + .object({ + name: z.string().optional(), + user_id: z.string().optional(), + }) + .optional() + .describe("Give these details only if you have them."), +}); + +export type CommunicationManager = z.infer; + +const communication_tools = (context_message: Message) => { + const allTools: RunnableToolFunctionWithParse[] = [ + zodFunction({ + function: (args) => search_user(args, context_message), + name: "search_user", + schema: SearchUserParams, + description: `Retrieve a user's details (email or platform IDs) by searching their name. + +Supported platforms: ['whatsapp', 'discord', 'email', 'events']`, + }), + zodFunction({ + function: (args) => send_message_to(args, context_message), + name: "send_message_to", + schema: SendMessageParams, + description: `Send a message to a user or relation using their config name or user ID. + +- **Current user's platform:** ${context_message.platform} +- If no platform is specified, use the current user's platform unless specified otherwise. +- If no \`user_name\` is provided, the message will be sent to the current user. +- Use \`search_user\` to obtain the \`user_id\`. +- Supported platforms: ['whatsapp', 'discord'] + +**Note:** When sending a message on behalf of someone else, mention who is sending it. For example, if Pooja asks you to remind Raj to drink water, send: "Pooja wanted to remind you to drink water."`, + }), + zodFunction({ + function: send_email, + schema: ResendParams, + description: `Send an email to a specified email address. + +- Confirm the recipient's email with the user before sending. +- Use \`search_user\` to get the email if only a name is provided. +- Do not invent an email address if none is found.`, + }), + ]; + + return allTools; +}; + +export async function communication_manager( + { + request, + prefered_platform, + prefered_recipient_details, + }: CommunicationManager, + context_message: Message +) { + const tools = communication_tools(context_message).concat( + memory_manager_init(context_message, "communications_manager") + ); + + const prompt = `You are a Communication Manager Tool. + +Your task is to route messages to the correct recipient. + +It is extremely important that the right message goes to the right user, and never to the wrong user. + +--- + +${memory_manager_guide("communications_manager")} + +You can use the \`memory_manager\` tool to remember user preferences, such as what the user calls certain contacts, to help you route messages better. + +--- + +**Default Platform (if not mentioned):** ${context_message.platform} + +**Configuration of All Users:** ${JSON.stringify(userConfigs)} + +**Can Access 'WhatsApp':** ${context_message.getUserRoles().includes("creator")} + +**Guidelines:** + +- If the user does not mention a platform, use the same platform as the current user. + +- Look for the recipient's details in the user configuration before checking WhatsApp users. + +- If the recipient is not on the current user's platform and the user can access WhatsApp, you may check if the recipient is on WhatsApp. Confirm the WhatsApp number (WhatsApp ID) with the user before sending the message. + +- Check WhatsApp only if the user can access it and the recipient is not found in the user config or if the user explicitly asks to send the message on WhatsApp. +`; + + const response = await ask({ + prompt, + message: `request: ${request} + + prefered_platform: ${prefered_platform} + + prefered_recipient_details: ${JSON.stringify(prefered_recipient_details)}`, + tools, + }); + + try { + return { + response: response.choices[0].message, + }; + } catch (error) { + return { + error, + }; + } +} + +export const communication_manager_tool = (context_message: Message) => + zodFunction({ + function: (args) => communication_manager(args, context_message), + name: "communication_manager", + schema: CommunicationManagerSchema, + description: `Communications Manager. + +This tool routes messages to the specified user on the appropriate platform. + +Use it to send messages to users on various platforms. + +Provide detailed information to ensure the message reaches the correct recipient. + +Include in your request the message content and the recipient's details. + +**Example:** + +- **User:** "Tell Pooja to call me." +- **Sender's Name:** Raj +- **Recipient's Name:** Pooja +- **Generated Request String:** "Raj wants to message Pooja 'call me'. Seems like he's in a hurry, so you can format it to sound urgent." +`, + }); diff --git a/tools/docker.ts b/tools/docker.ts new file mode 100644 index 0000000..039d87c --- /dev/null +++ b/tools/docker.ts @@ -0,0 +1,24 @@ +import { z } from "zod"; + +// run bash command in docker container +export const RunCommandParams = z.object({ + command: z.string().describe("the command to run"), +}); +export type RunCommandParams = z.infer; +export async function run_command({ command }: RunCommandParams) { + const { exec } = require("child_process"); + return new Promise((resolve, reject) => { + exec(command, (error: any, stdout: any, stderr: any) => { + if (error) { + console.log(`error: ${error.message}`); + reject(error.message); + } + if (stderr) { + console.log(`stderr: ${stderr}`); + reject(stderr); + } + console.log(`stdout: ${stdout}`); + resolve(stdout); + }); + }); +} diff --git a/tools/events.ts b/tools/events.ts new file mode 100644 index 0000000..f84cfb6 --- /dev/null +++ b/tools/events.ts @@ -0,0 +1,1158 @@ +// event_tools.ts +import YAML from "yaml"; +import { z } from "zod"; +import { v4 as uuidv4 } from "uuid"; +import { Message } from "../interfaces/message"; +import { eventManager } from "../interfaces/events"; +import fs from "fs/promises"; +import path from "path"; +import { discordAdapter } from "../interfaces"; +import { RunnableToolFunctionWithParse } from "openai/lib/RunnableFunction.mjs"; +import { getTools, zodFunction } from "."; +import { ask } from "./ask"; +import { get_actions } from "./actions"; +import { pathInDataDir, userConfigs } from "../config"; +import { memory_manager_guide, memory_manager_init } from "./memory-manager"; +import { buildSystemPrompts } from "../assistant/system-prompts"; + +// Paths to the JSON files +const LISTENERS_FILE_PATH = pathInDataDir("listeners.json"); +const EVENTS_FILE_PATH = pathInDataDir("events.json"); + +// Define schema for creating an event +export const CreateEventParams = z.object({ + eventId: z + .string() + .describe( + "The unique identifier for the event. Make this relevant to the event." + ), + description: z + .string() + .min(1, "description is required") + .describe("Short description of the event."), +}); + +// Type for creating an event +export type CreateEventParams = z.infer; + +// Define schema for creating an event listener +export const CreateEventListenerParams = z + .object({ + eventId: z.string().min(1, "eventId is required"), + description: z + .string() + .min(1, "description is required") + .describe("Short description of what the event listener does."), + instruction: z + .string() + .min(1, "instruction is required") + .describe( + "Detailed instructions on what to do with the event payload when triggered." + ) + .optional(), + template: z + .string() + .min(1, "template is required") + .describe( + "A string template to format the event payload. Use double curly braces to reference payload variables, e.g., {{variableName}}." + ) + .optional(), + tool_names: z + .array(z.string()) + .optional() + .describe( + `Names of the tools required to execute the instruction when the event is triggered. + Each of these should look something like "home_assistant_manager" or "calculator" and NOT "function:home_assistant_manager" or "function.calculator".` + ), + autoStopAfterSingleEvent: z + .boolean() + .default(true) + .describe( + `Auto stop after the first event is triggered. Defaults to true. Cannot be set with autoStopAfterDelay.` + ) + .optional(), + autoStopAfterDelay: z + .number() + .positive() + .int() + .optional() + .describe( + "Time in seconds after which the listener auto stops. Cannot be set with autoStopAfterSingleEvent." + ), + notify: z + .boolean() + .describe( + "Whether to notify the user or not, should be true by default." + ), + }) + .refine( + (data) => { + const hasInstruction = !!data.instruction; + const hasTemplate = !!data.template; + return hasInstruction !== hasTemplate; // Either instruction or template must be present, but not both + }, + { + message: + "Either 'instruction' or 'template' must be provided, but not both.", + } + ); + +// Type for creating an event listener +export type CreateEventListenerParams = z.infer< + typeof CreateEventListenerParams +>; + +// Define schema for searching event listeners +export const SearchEventListenersParams = z.object({ + userId: z.string().optional(), + eventId: z.string().optional(), +}); + +// Type for searching event listeners +export type SearchEventListenersParams = z.infer< + typeof SearchEventListenersParams +>; + +// Define schema for removing an event listener +const RemoveEventListenerParamsSchema = z.object({ + listenerId: z.string().min(1, "listenerId is required"), +}); + +// Type for removing an event listener +type RemoveEventListenerParams = z.infer< + typeof RemoveEventListenerParamsSchema +>; + +/** + * Removes an event listener by its listenerId by fully deleting it. + * @param params - Parameters containing the listenerId. + * @returns A JSON object confirming removal or an error. + */ +export async function remove_event_listener_tool( + params: RemoveEventListenerParams +): Promise { + // Validate parameters using zod + const parsed = RemoveEventListenerParamsSchema.safeParse(params); + if (!parsed.success) { + return { error: parsed.error.errors }; + } + + const { listenerId } = parsed.data; + + const listener = listenersMap.get(listenerId); + + if (!listener) { + return { + error: `❌ Listener with ID "${listenerId}" not found.`, + }; + } + + // Fully remove the listener + await removeListener(listener.id, listener.eventId); + + return { + message: `✅ Listener with ID "${listenerId}" removed successfully.`, + }; +} + +// Define schema for updating event description +export const UpdateEventDescriptionParams = z.object({ + eventId: z.string().min(1, "eventId is required"), + description: z.string().min(1, "description is required"), +}); + +// Type for updating event description +export type UpdateEventDescriptionParams = z.infer< + typeof UpdateEventDescriptionParams +>; + +// Define schema for updating an event listener +export const UpdateEventListenerParams = z + .object({ + listenerId: z.string().min(1, "listenerId is required"), + eventId: z.string().min(1, "eventId is required"), + description: z.string().min(1, "description is required"), + instruction: z + .string() + .min(1, "instruction is required") + .describe( + "Detailed instructions on what to do with the event payload when triggered." + ) + .optional(), + template: z + .string() + .min(1, "template is required") + .describe( + "A string template to format the event payload. Use double curly braces to reference payload variables, e.g., {{variableName}}." + ) + .optional(), + tool_names: z + .array(z.string()) + .optional() + .describe( + "Names of the tools required to execute the instruction when the event is triggered." + ), + autoStopAfterSingleEvent: z + .boolean() + .optional() + .describe( + `Auto stop after the first event is triggered. Cannot be set with autoStopAfterDelay.` + ), + autoStopAfterDelay: z + .number() + .positive() + .int() + .optional() + .describe( + "Time in seconds after which the listener auto stops. Cannot be set with autoStopAfterSingleEvent." + ), + }) + .refine( + (data) => { + const hasInstruction = !!data.instruction; + const hasTemplate = !!data.template; + return hasInstruction !== hasTemplate; // Either instruction or template must be present, but not both + }, + { + message: + "Either 'instruction' with 'tool_names' or 'template' must be provided, but not both.", + } + ); + +// Type for updating an event listener +export type UpdateEventListenerParams = z.infer< + typeof UpdateEventListenerParams +>; + +// Define the structure of an Event +interface Event { + eventId: string; + description: string; + userId: string; // Associate the event with a user + setup_done: boolean; // Added field to indicate if setup is done + last_triggered?: string; // ISO string for serialization + last_payload?: Record; // Store the last payload +} + +// Define the structure of an Event Listener +interface EventListener { + id: string; + eventId: string; + userId: string; + description: string; + instruction?: string; + template?: string; // New field for static event listeners + options: ListenerOptions; + tool_names?: string[]; + created_at: string; // ISO string for serialization + expires_in?: number; // seconds + callback?: EventCallback; // Not serialized + notify: boolean; +} + +// Options for listener +interface ListenerOptions { + autoStopAfterSingleEvent?: boolean; + autoStopAfterDelay?: number; // seconds +} + +// Define the type for the event callback +type EventCallback = (payload: Record) => void; + +// In-memory storage for events and event listeners +const eventsMap: Map = new Map(); +const listenersMap: Map = new Map(); + +// Helper function to load events from the JSON file +async function loadEventsFromFile() { + try { + const data = await fs.readFile(EVENTS_FILE_PATH, "utf-8"); + const parsed = JSON.parse(data) as Event[]; + parsed.forEach((event) => { + eventsMap.set(event.eventId, event); + }); + console.log(`✅ Loaded ${eventsMap.size} events from ${EVENTS_FILE_PATH}`); + } catch (error: any) { + if (error.code === "ENOENT") { + // File does not exist, create an empty file + await saveEventsToFile(); + console.log(`📄 Created new events file at ${EVENTS_FILE_PATH}`); + } else { + console.error(`❌ Failed to load events from file: ${error.message}`); + } + } +} + +// Helper function to save events to the JSON file +async function saveEventsToFile() { + const data = JSON.stringify(Array.from(eventsMap.values()), null, 2); + await fs.writeFile(EVENTS_FILE_PATH, data, "utf-8"); +} + +// Helper function to load listeners from the JSON file +async function loadListenersFromFile() { + try { + const data = await fs.readFile(LISTENERS_FILE_PATH, "utf-8"); + const parsed = JSON.parse(data) as EventListener[]; + parsed.forEach((listener) => { + // Check if listener has expired + if (listener.expires_in) { + const createdAt = new Date(listener.created_at).getTime(); + const expiresInMs = listener.expires_in * 1000; + const currentTime = Date.now(); + if (currentTime > createdAt + expiresInMs) { + console.log( + `🔕 Listener "${listener.id}" for event "${listener.eventId}" by user "${listener.userId}" has expired and will not be loaded.` + ); + return; // Skip loading expired listener + } + } + + listenersMap.set(listener.id, listener); + registerListener(listener); + }); + console.log( + `✅ Loaded ${listenersMap.size} listeners from ${LISTENERS_FILE_PATH}` + ); + } catch (error: any) { + if (error.code === "ENOENT") { + // File does not exist, create an empty file + await saveListenersToFile(); + console.log(`📄 Created new listeners file at ${LISTENERS_FILE_PATH}`); + } else { + console.error(`❌ Failed to load listeners from file: ${error.message}`); + } + } +} + +// Helper function to save listeners to the JSON file +async function saveListenersToFile() { + const data = JSON.stringify(Array.from(listenersMap.values()), null, 2); + await fs.writeFile(LISTENERS_FILE_PATH, data, "utf-8"); +} + +// Function to register a listener with the eventManager +function registerListener(listener: EventListener) { + const { eventId, description, userId, options, tool_names, notify } = + listener; + + const callback: EventCallback = async ( + payload: Record + ) => { + const event = eventsMap.get(eventId); + if (event) { + event.last_triggered = new Date().toISOString(); + event.last_payload = payload; + await saveEventsToFile(); + } + try { + // Check if listener has expired + if (listener.expires_in) { + const createdAt = new Date(listener.created_at).getTime(); + const expiresInMs = listener.expires_in * 1000; + const currentTime = Date.now(); + if (currentTime > createdAt + expiresInMs) { + console.log( + `🔕 Listener "${listener.id}" for event "${eventId}" by user "${userId}" has expired and will be removed.` + ); + await removeListener(listener.id, eventId); + return; // Ignore trigger + } + } + + // Recreate the Message instance using discordAdapter + const contextMessage: Message = + await discordAdapter.createMessageInterface(userId); + if (!contextMessage) { + console.error( + `❌ Unable to create Message interface for user "${userId}".` + ); + return; + } + + if (listener.template) { + // Handle static event listener with template + const formattedMessage = renderTemplate(listener.template, payload); + await contextMessage.send({ content: formattedMessage }); + + // Handle auto-stop options + if (options.autoStopAfterSingleEvent) { + await removeListener(listener.id, eventId); + } + return formattedMessage; + // Expiry is handled via periodic cleanup + } else if (listener.instruction) { + // Handle dynamic event listener with instruction and tools + const u_tool_names = Array.from( + new Set([...(tool_names ?? []), "event_manager"]) + ); + let tools = getTools( + contextMessage.author.username, + contextMessage + ).filter( + (tool) => + tool.function.name && u_tool_names?.includes(tool.function.name) + ) as RunnableToolFunctionWithParse[] | undefined; + + tools = tools?.length ? tools : undefined; + + const is_voice = listener.eventId === "on_voice_message"; + + if (is_voice) { + tools = getTools( + contextMessage.author.username, + contextMessage + ) as RunnableToolFunctionWithParse[]; + } + + console.log("Running ASK for event listener: ", listener.description); + console.log("Payload: ", payload); + + const system_prompts = is_voice + ? await buildSystemPrompts(contextMessage) + : undefined; + + const prompt_heading = system_prompts + ? "" + : `You are an Event Handler.`; + + let prompt = `${prompt_heading} + You are called when an event triggers. Your task is to execute the user's instruction based on the triggered event and reply with the text to display as a notification to the user. + + **Guidelines:** + + - **Notification to User:** + - Any message you reply with will automatically be sent to the user as a notification. + - Do **not** indicate in the text that it is a notification. + + - **Using Tools:** + - You have access to the necessary tools to execute the instruction; use them as needed. + - You also have access to the \`event_manager\` tool if you need to manage events or listeners (use it only if necessary). + + - **Sending Messages:** + - **To the Current User:** + - Do **not** ask \`communication_manager\` tool. (if available) + - Simply reply with the message you want to send. + - **To Other Users:** + - Use the \`communication_manager\` tool. (if available) + - The message you reply with will still be sent to the current user as a notification. + + **Example:** + + - **Instruction:** "When you get an email from John, tell John on WhatsApp that you got the email." + - **Steps:** + 1. Use the \`communication_manager\` tool to send a message to John on WhatsApp. + - Use the WhatsApp ID from the payload to send the message instead of searching for the user. + 2. Reply to the current user with "I have sent a message to John on WhatsApp that you got the email." + + **Currently Triggered Event:** + + - **Event ID:** ${eventId} + - **Description:** ${description} + - **Payload:** ${JSON.stringify(payload, null, 2)} + - **Will Auto Notify Creator of Listener:** ${notify ? "Yes" : "No"} + - **Instruction:** ${listener.instruction} + + **Important Note:** + + - If the above event and payload does **not** match the instruction, reply with the string **"IGNORE"** to skip executing the instruction for this payload. + + **Action Required:** + + - Follow the instruction provided. + - Return the notification text based on the instruction. + `; + + const voice_prompt = `You are in voice trigger mode. + + The voice event that triggered this is: + - Event ID: ${eventId} + - Description: ${description} + - Payload: ${JSON.stringify(payload, null, 2)} + + Follow the transcript provided in the payload. + Reply only in plain text without markdown or any other formatting. + `; + + if (system_prompts) { + prompt = `${system_prompts.map((p) => p.content).join("\n\n")}`; + // console.log("Voice system Prompt: ", prompt); + } + + const response = !is_voice + ? await ask({ + model: "gpt-4o-mini", + prompt, + tools, + }) + : await ask({ + model: "gpt-4o-mini", + prompt, + message: voice_prompt, + seed: `voice-anya-${listener.id}-${eventId}`, + tools, + }); + + const content = response.choices[0].message.content ?? undefined; + + const ignore = content?.includes("IGNORE"); + + if (ignore) { + console.log("Ignoring event: ", content); + return; + } + + // Send a message to the user indicating the event was triggered + if (notify) await contextMessage.send({ content }); + else console.log("Silenced Notification: ", content); + + // Handle auto-stop options + if (options.autoStopAfterSingleEvent) { + await removeListener(listener.id, eventId); + } + + return content; + // Expiry is handled via periodic cleanup + } else { + console.error( + `❌ Listener "${listener.id}" has neither 'instruction' nor 'template' defined.` + ); + } + } catch (error) { + console.error(`Error sending message to user ${userId}:`, error); + } + }; + + // Assign the callback to the listener for future reference + listener.callback = callback; + + // Register the callback with eventManager + eventManager.on(eventId, callback); +} + +export const MarkSetupAsDoneParams = z.object({ + eventId: z.string().min(1, "eventId is required"), +}); + +export type MarkSetupAsDoneParams = z.infer; + +/** + * Marks the setup of an event as done by setting 'setup_done' to true. + * @param params - Parameters containing the eventId. + * @param contextMessage - The message context to identify the user. + * @returns A JSON object confirming the update or an error. + */ +export async function mark_setup_as_done( + params: MarkSetupAsDoneParams, + contextMessage: Message +): Promise { + // Validate parameters using zod + const parsed = MarkSetupAsDoneParams.safeParse(params); + if (!parsed.success) { + return { error: parsed.error.errors }; + } + + const { eventId } = parsed.data; + + // Get the userId from contextMessage + const userId: string = contextMessage.author.id; + + // Check if the event exists and is owned by the user + const event = eventsMap.get(eventId); + if (!event) { + return { error: `❌ Event with ID "${eventId}" does not exist.` }; + } + + if (event.userId !== userId) { + return { error: `❌ You do not have permission to update this event.` }; + } + + // Update the setup_done field + event.setup_done = true; + eventsMap.set(eventId, event); + await saveEventsToFile(); + + return { + eventId, + setup_done: event.setup_done, + message: "✅ Event setup marked as done successfully.", + }; +} + +/** + * Simple template renderer that replaces {{key}} with corresponding values from payload. + * @param template - The string template containing placeholders like {{key}}. + * @param payload - The payload containing key-value pairs. + * @returns The formatted string with placeholders replaced by payload values. + */ +function renderTemplate( + template: string, + payload: Record +): string { + return template.replace(/{{\s*([^}]+)\s*}}/g, (_, key) => { + return (payload[key.trim()] || `{{${key.trim()}}}`) as string; + }); +} + +// Function to fully remove a listener by its ID and eventId +async function removeListener(listenerId: string, eventId: string) { + const listener = listenersMap.get(listenerId); + if (!listener) return; + + // Unregister the callback from eventManager + if (listener.callback) { + eventManager.off(eventId, listener.callback); + } + + // Remove from storage + listenersMap.delete(listenerId); + await saveListenersToFile(); + + console.log( + `🔕 Listener "${listener.id}" for event "${listener.eventId}" by user "${listener.userId}" has been removed.` + ); +} + +// Initialize events and listeners by loading from the files +loadEventsFromFile(); +loadListenersFromFile(); + +// Periodic cleanup for expired listeners +const CLEANUP_INTERVAL_MS = 60 * 1000; // 1 minute + +setInterval(async () => { + const now = Date.now(); + const expiredListeners: string[] = []; + + listenersMap.forEach((listener, id) => { + if (listener.expires_in) { + const createdAt = new Date(listener.created_at).getTime(); + const expiresInMs = listener.expires_in * 1000; + if (now > createdAt + expiresInMs) { + expiredListeners.push(id); + } + } + }); + + for (const id of expiredListeners) { + const listener = listenersMap.get(id); + if (listener) { + console.log( + `🔕 Listener "${listener.id}" for event "${listener.eventId}" by user "${listener.userId}" has expired and will be removed.` + ); + await removeListener(id, listener.eventId); + } + } + + if (expiredListeners.length > 0) { + await saveListenersToFile(); + } +}, CLEANUP_INTERVAL_MS); + +/** + * Creates an event. + * @param params - Parameters for creating the event. + * @param contextMessage - The message context from which the event is created. + * @returns A JSON object containing the event details and a success message, or an error. + */ +export async function create_event( + params: CreateEventParams, + contextMessage: Message +): Promise { + const parsed = CreateEventParams.safeParse(params); + if (!parsed.success) { + return { error: parsed.error.errors }; + } + + let { eventId, description } = parsed.data; + + // Get the userId from contextMessage + const userId: string = contextMessage.author.id; + + if (eventsMap.has(eventId)) { + return { error: `❌ Event with ID "${eventId}" already exists.` }; + } + + const event: Event = { + eventId, + description, + userId, // Assign userId to the event + setup_done: false, // Initialize setup_done to false + }; + + eventsMap.set(eventId, event); + await saveEventsToFile(); + + return { + eventId, + description, + userId, + setup_done: event.setup_done, // Include setup_done in the response + message: "✅ Event created successfully.", + }; +} + +// 1. Define schema for getting events +export const GetEventsParams = z.object({}); + +export type GetEventsParams = z.infer; + +// 2. Implement the get_events function +export async function get_events( + params: GetEventsParams, + contextMessage: Message +): Promise< + | { + events: Event[]; + } + | { error: string } +> { + // Get the userId from contextMessage + const userId: string = contextMessage.author.id; + + // Get all events created by this user + const userEvents = Array.from(eventsMap.values()).filter( + (event) => event.userId === userId + ); + + return { + events: userEvents, + }; +} + +/** + * Creates an event listener. + * @param params - Parameters for creating the listener. + * @param contextMessage - The message context from which the listener is created. + * @returns A JSON object containing the listener details and a success message, or an error. + */ +export async function create_event_listener( + params: CreateEventListenerParams, + contextMessage: Message +): Promise { + // Validate parameters using zod + const parsed = CreateEventListenerParams.safeParse(params); + if (!parsed.success) { + return { error: parsed.error.errors }; + } + + let { + eventId, + description, + instruction, + template, + tool_names, + autoStopAfterSingleEvent = true, + autoStopAfterDelay, + notify, + } = parsed.data; + + // Check if the event exists + if (!eventsMap.has(eventId)) { + return { error: `❌ Event with ID "${eventId}" does not exist.` }; + } + + // Get the userId from contextMessage + const userId: string = contextMessage.author.id; + + // Create a unique listener ID + const listenerId = uuidv4(); + + // Calculate expires_in if autoStopAfterDelay is set + const expires_in = autoStopAfterDelay ? autoStopAfterDelay : undefined; + + // Create the listener object + const listener: EventListener = { + id: listenerId, + eventId, + userId, + description, + instruction, + template, // Assign template if provided + options: { + autoStopAfterSingleEvent, + autoStopAfterDelay, + }, + tool_names, + created_at: new Date().toISOString(), + expires_in, + notify, + }; + + // Store the listener in the in-memory storage + listenersMap.set(listener.id, listener); + + // Register the listener with eventManager + registerListener(listener); + + // Save the updated listeners to the JSON file + await saveListenersToFile(); + + // Return the listener details as confirmation + return { + listenerId, + eventId, + userId, + description, + instruction, + template, // Include template in the response if provided + created_at: listener.created_at, + expires_in: listener.expires_in, + message: "✅ Event listener created successfully.", + }; +} + +/** + * Retrieves all event listeners created by the user. + * @param params - Parameters for getting event listeners (none required). + * @param contextMessage - The message context to identify the user. + * @returns A JSON array of the user's event listeners or an error. + */ +export async function get_event_listeners( + params: {}, + contextMessage: Message +): Promise { + // Get the userId from contextMessage + const userId: string = contextMessage.author.id; + + // Get all listeners created by this user + const userListeners = Array.from(listenersMap.values()).filter( + (listener) => listener.userId === userId + ); + + return { + listeners: userListeners, + }; +} + +/** + * Updates the description of an event. + * @param params - Parameters containing the eventId and new description. + * @param contextMessage - The message context to identify the user. + * @returns A JSON object confirming the update or an error. + */ +export async function update_event_description( + params: UpdateEventDescriptionParams, + contextMessage: Message +): Promise { + // Validate parameters using zod + const parsed = UpdateEventDescriptionParams.safeParse(params); + if (!parsed.success) { + return { error: parsed.error.errors }; + } + + const { eventId, description } = parsed.data; + + // Get the userId from contextMessage + const userId: string = contextMessage.author.id; + + // Check if the event exists and is owned by the user + const event = eventsMap.get(eventId); + if (!event) { + return { error: `❌ Event with ID "${eventId}" does not exist.` }; + } + + if (event.userId !== userId) { + return { error: `❌ You do not have permission to update this event.` }; + } + + // Update the event description + event.description = description; + eventsMap.set(eventId, event); + await saveEventsToFile(); + + return { + eventId, + description, + message: "✅ Event description updated successfully.", + }; +} + +/** + * Updates the details of an event listener. + * @param params - Parameters containing the listenerId and fields to update. + * @param contextMessage - The message context to identify the user. + * @returns A JSON object confirming the update or an error. + */ +export async function update_event_listener( + params: UpdateEventListenerParams, + contextMessage: Message +): Promise { + // Validate parameters using zod + const parsed = UpdateEventListenerParams.safeParse(params); + if (!parsed.success) { + return { error: parsed.error.errors }; + } + + const { + listenerId, + eventId, + description, + instruction, + template, + tool_names, + autoStopAfterSingleEvent, + autoStopAfterDelay, + } = parsed.data; + + // Get the userId from contextMessage + const userId: string = contextMessage.author.id; + + // Find the listener + const listener = listenersMap.get(listenerId); + if (!listener) { + return { error: `❌ Listener with ID "${listenerId}" not found.` }; + } + + // Ensure the listener belongs to the user + if (listener.userId !== userId) { + return { error: `❌ You do not have permission to update this listener.` }; + } + + // If eventId is being updated, ensure the new event exists + if (eventId !== listener.eventId) { + if (!eventsMap.has(eventId)) { + return { error: `❌ Event with ID "${eventId}" does not exist.` }; + } + // Unregister the old event + if (listener.callback) { + eventManager.off(listener.eventId, listener.callback); + } + listener.eventId = eventId; + // Register the new event + registerListener(listener); + } + + // Update other fields + listener.description = description; + listener.instruction = instruction; + listener.template = template; // Update template if provided + listener.tool_names = tool_names; + if (autoStopAfterSingleEvent !== undefined) { + listener.options.autoStopAfterSingleEvent = autoStopAfterSingleEvent; + } + if (autoStopAfterDelay !== undefined) { + listener.options.autoStopAfterDelay = autoStopAfterDelay; + listener.expires_in = autoStopAfterDelay; + } else if (autoStopAfterDelay === undefined && template) { + // If updating and template is provided without autoStopAfterDelay, remove expires_in + listener.expires_in = undefined; + } + + listenersMap.set(listenerId, listener); + await saveListenersToFile(); + + return { + listenerId, + eventId, + userId, + description, + instruction, + template, + created_at: listener.created_at, + expires_in: listener.expires_in, + message: "✅ Event listener updated successfully.", + }; +} + +// Export the tools as RunnableToolFunctionWithParse array +export const event_tools: ( + context_message: Message, + valid_tool_names: string[] +) => RunnableToolFunctionWithParse[] = (context_message) => [ + zodFunction({ + name: "create_event", + function: (args) => create_event(args, context_message), + schema: CreateEventParams, + description: `Creates a new event.`, + }), + zodFunction({ + name: "create_event_listener", + function: (args) => create_event_listener(args, context_message), + schema: CreateEventListenerParams, + description: `Create an event listener to respond to specific events and notify the user. +Before creating a new listener, use 'get_event_listeners' to check for existing ones. +If a similar listener exists, confirm whether the user wants to proceed with a new one. +You can create either a dynamic listener using 'instruction' and 'tool_names' or a static listener using a 'template'. + +Examples: +1. Dynamic Listener: + - User: "Turn on the lights when I get home" + - Description: "Turns on lights when the user arrives home" + - Instruction: "Turn on the lights and welcome the user" + - Required Tools: ["home_assistant_manager"] + +Notes: +- When using 'template', make sure you confirm from that user that the payload variables are correct and would actually be there when the event is triggered. +- When using 'template', ensure to use double curly braces to reference payload variables, e.g., {{variableName}}. +`, + }), + zodFunction({ + name: "update_event_description", + function: (args) => update_event_description(args, context_message), + schema: UpdateEventDescriptionParams, + description: `Updates the description of an existing event.`, + }), + zodFunction({ + name: "update_event_listener", + function: (args) => update_event_listener(args, context_message), + schema: UpdateEventListenerParams, + description: `Updates the details of an existing event listener. +This needs all details of the old listener to update it. +This basically replaces the old listener with the new one created by the params that are passed. + +You can update either the 'instruction' for dynamic listeners or the 'template' for static listeners. + +When updating with a 'template', ensure to use double curly braces to reference payload variables, e.g., {{variableName}}. +`, + }), + zodFunction({ + name: "remove_event_listener", + function: (args) => remove_event_listener_tool(args), + schema: RemoveEventListenerParamsSchema, + description: `Removes an event listener by specifying the listener ID.`, + }), + zodFunction({ + name: "mark_setup_as_done", + function: (args) => mark_setup_as_done(args, context_message), + schema: MarkSetupAsDoneParams, + description: `Marks the setup of an event as done by setting 'setup_done' to true.`, + }), +]; + +// make event manager tool for the above tools +export const EventManagerSchema = z.object({ + request: z + .string() + .describe( + "What the user wants to do relatingto external events listeners or automation" + ), + tool_names: z + .array(z.string()) + .optional() + .describe("Names of the tools required to execute the instruction."), +}); + +type EventManagerSchema = z.infer; + +export async function event_manager( + { request, tool_names }: EventManagerSchema, + context_message: Message +): Promise { + const tools = event_tools(context_message, tool_names ?? []).concat( + memory_manager_init(context_message, "events_manager") + ); + + const userConfigData = userConfigs.find((config) => + config.identities.find((id) => id.id === context_message.author.id) + ); + + try { + const all_actions = await get_actions({}, context_message); + + const all_events = await get_events({}, context_message); + + const all_event_listeners = await get_event_listeners({}, context_message); + + const response = await ask({ + model: "gpt-4o-mini", + prompt: `You are an Events Manager. + +Each event can have multiple listeners, and each listener can have multiple actions. + +A listener is a function that reacts to an event, performs an action, and automatically generates a notification string to send to the user. (The user will be automatically notified with this string.) + +The webhook URL is \`https://events.raj.how/events/{event_id}\`, which triggers all listeners for that event ID. When you create a new event or the user requests the URL for a specific event, share this URL with the user so they can set up the webhook. Once the webhook is set up, you don't need to send the webhook URL to the user again. + +---- + +${memory_manager_guide("events_manager")} + +---- + +**Examples & Use Cases:** + +1. **Action on Location Event:** + - User can create an event called "reached_home" and set up a listener for this event to turn on the lights when they reach home. + - Or add a listener to send a message to the user when they reach home. + - Or any action when the event "reached_home" is triggered. + +2. **Action on WhatsApp Event:** + - **User:** "When I get a message on WhatsApp from Raj, tell him that I'm driving." + - **Event:** "got_whatsapp_message" + - **Listener:** "When Raj is the sender, reply with 'I'm driving.' using the \`communication_manager\` tool and notify the user that you replied with 'I'm driving.'" + - **Tool Names:** \`["communication_manager"]\` + +**Guidelines:** + +- When the user says something like: "Turn on the lights when I reach home": + 1. **Check Existing Events:** + - Retrieve all events to see if any match the user's request. + - If a matching event exists and \`setup_done\` is \`true\`, use this event ID to create a listener. + - If \`setup_done\` is \`false\`, share the webhook URL with the user for setup and wait until \`setup_done\` is \`true\` before creating listeners. + 2. **Create New Event:** + - If no matching event exists, create a new event. + - Set \`setup_done\` to \`false\` and share the webhook URL with the user for setup. + - Do not create listeners until the user confirms the webhook setup and \`setup_done\` is marked as \`true\`. + +**Important Notes:** + +- **Do not create listeners for events where \`setup_done\` is \`false\`.** + +- **Webhook Setup:** + - If \`setup_done\` is \`false\` for an event, share the webhook URL with the user for setup. + - Once the user confirms the webhook is set up, mark \`setup_done\` as \`true\`. + - Do not share the webhook URL again if \`setup_done\` is \`true\`; proceed with setting up listeners. + +- **Event Management:** + - You can create, update, and remove events and event listeners. + - Try to use existing events whenever possible. Create new ones only when absolutely necessary. + +- **Action Similarity:** + - Review the actions provided by the \`action_manager\`. If any action is too similar to an event listener, point this out to the user. + +- **Fulfill User Requests:** + - Your primary goal is to fulfill the user's requests based on the above guidelines. + +**Additional Information:** + +- **Current Date:** ${new Date().toISOString()} + +- **Current User Details:** ${JSON.stringify(userConfigData)} + +- **Actions Set Up by \`action_manager\`:** + ${JSON.stringify(all_actions)} + +- **Already Existing Valid Available Events:** + ${JSON.stringify(all_events)} + +- **Valid Event Listeners:** + ${JSON.stringify(all_event_listeners)} + +- **Tool Names List for Creating a Listener:** + ${JSON.stringify(tool_names)} + `, + tools, + seed: context_message.channelId, + message: request, + }); + + console.log(response.choices[0].message.content); + + return { + response: response.choices[0].message.content, + }; + } catch (error) { + console.error("Error in event_manager:", error); + return { + error, + }; + } +} + +export function return_current_events() { + return Array.from(eventsMap.values()); +} +export function return_current_listeners() { + return Array.from(listenersMap.values()); +} diff --git a/tools/files.ts b/tools/files.ts new file mode 100644 index 0000000..45b5989 --- /dev/null +++ b/tools/files.ts @@ -0,0 +1,75 @@ +import { Client } from "minio"; +import { z } from "zod"; + +if (!process.env.MINIO_ACCESS_KEY || !process.env.MINIO_SECRET_KEY) { + throw new Error( + "MINIO_ACCESS_KEY or MINIO_SECRET_KEY not found in environment variables" + ); +} + +// Initialize MinIO client +const minioClient = new Client({ + endPoint: "s3.raj.how", + port: 443, + useSSL: true, + accessKey: process.env.MINIO_ACCESS_KEY, + secretKey: process.env.MINIO_SECRET_KEY, +}); + +// Define schema for uploading file +export const UploadFileParams = z.object({ + bucketName: z.string().default("public").optional(), + fileName: z.string().describe("make sure this is unique"), + filePath: z + .string() + .describe( + "put all files inside 'anya' directory by default unless user specifies otherwise" + ), +}); +export type UploadFileParams = z.infer; + +// Define schema for getting file list +export const GetFileListParams = z.object({ + bucketName: z.string().default("public").optional(), +}); +export type GetFileListParams = z.infer; + +// Upload file to MinIO bucket and return public URL +export async function upload_file({ + bucketName = "public", + fileName, + filePath, +}: UploadFileParams) { + try { + await minioClient.fPutObject(bucketName, fileName, filePath); + const publicUrl = `https://s3.raj.how/${bucketName}/${fileName}`; + return { + publicUrl, + }; + } catch (error) { + return { + error: JSON.stringify(error), + }; + } +} + +// Get list of all files in the bucket and return their public URLs +export async function get_file_list({ + bucketName = "public", +}: GetFileListParams) { + try { + const fileUrls: string[] = []; + const stream = await minioClient.listObjects(bucketName, "", true); + + for await (const obj of stream) { + const fileUrl = `https://s3.raj.how/${bucketName}/${obj.name}`; + fileUrls.push(fileUrl); + } + + return fileUrls; + } catch (error) { + return { + error: JSON.stringify(error), + }; + } +} diff --git a/tools/google.ts b/tools/google.ts new file mode 100644 index 0000000..7463416 --- /dev/null +++ b/tools/google.ts @@ -0,0 +1,57 @@ +import { getJson } from "serpapi"; +import { z } from "zod"; + +export const GoogleSearchParams = z.object({ + query: z.string(), + engine: z + .enum([ + "google_news", + "google_scholar", + "google_images", + "google_flights", + "google_jobs", + "google_videos", + "google_local", + "google_maps", + "google_shopping", + ]) + .describe("search engine"), + type: z + .enum([ + "news_results", + "organic_results", + "local_results", + "knowledge_graph", + "recipes_results", + "shopping_results", + "jobs_results", + "inline_videos", + "inline_images", + "all", + ]) + .describe("type of results that correspond the selected search engine"), + n: z.number().optional().describe("number of results"), +}); +export type GoogleSearchParams = z.infer; +export async function search({ query, type, n, engine }: GoogleSearchParams) { + if (!process.env.SEARCH_API_KEY) + return { response: "missing SEARCH_API_KEY env var" }; + + const res = await getJson({ + engine: engine ?? "google", + q: query, + api_key: process.env.SEARCH_API_KEY, + num: n, + }); + + if (type === "all") { + return res; + } + + if (res[type]) { + return res[type]; + } + return { + response: `no results, for the specified type ${type}, try a different type maybe`, + }; +} diff --git a/tools/home.ts b/tools/home.ts new file mode 100644 index 0000000..3431dbe --- /dev/null +++ b/tools/home.ts @@ -0,0 +1,393 @@ +import { z } from "zod"; +import axios, { AxiosError } from "axios"; +import { zodFunction } from "."; +import { + RunnableToolFunction, + RunnableToolFunctionWithParse, +} from "openai/lib/RunnableFunction.mjs"; +import Fuse from "fuse.js"; +import { ask } from "./ask"; +import { Message } from "../interfaces/message"; +import { memory_manager_guide, memory_manager_init } from "./memory-manager"; + +// Global axios config for Home Assistant API +const homeAssistantUrl = "https://home.raj.how"; +const token = process.env.HA_KEY; + +const apiClient = axios.create({ + baseURL: `${homeAssistantUrl}/api`, + headers: { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + }, +}); + +// -------------------- Caching Utility -------------------- // + +type CacheEntry = { + data: T; + timestamp: number; +}; + +class AsyncCache { + private cache: CacheEntry | null = null; + private fetchFunction: () => Promise; + private refreshing: boolean = false; + private refreshInterval: number; // in milliseconds + + constructor( + fetchFunction: () => Promise, + refreshInterval: number = 5 * 60 * 1000 + ) { + // Default refresh interval: 5 minutes + this.fetchFunction = fetchFunction; + this.refreshInterval = refreshInterval; + } + + async get(): Promise { + if (this.cache) { + // Return cached data immediately + this.refreshInBackground(); + return this.cache.data; + } else { + // No cache available, fetch data and cache it + const data = await this.fetchFunction(); + this.cache = { data, timestamp: Date.now() }; + return data; + } + } + + private async refreshInBackground() { + if (this.refreshing) return; // Prevent multiple simultaneous refreshes + this.refreshing = true; + + // Perform the refresh without blocking the main thread + this.fetchFunction() + .then((data) => { + this.cache = { data, timestamp: Date.now() }; + }) + .catch((error) => { + console.error("Error refreshing cache:", error); + // Optionally, handle the error (e.g., keep the old cache) + }) + .finally(() => { + this.refreshing = false; + }); + } +} + +// -------------------- Memoized Functions -------------------- // + +// 1. Fetch all available services with caching +export async function getAllServicesRaw() { + try { + const response = await apiClient.get("/services"); + return response.data; + } catch (error) { + console.error("Error fetching services:", error); + throw error; + } +} + +const servicesCache = new AsyncCache(getAllServicesRaw); + +export async function getAllServices() { + try { + const services = await servicesCache.get(); + return services; + } catch (error) { + return { error }; + } +} + +// 2. Fetch all devices and their valid states and services with caching +export async function getAllDevicesRaw() { + try { + const response = await apiClient.get("/states"); + const services = await getAllServicesRaw(); + + const devices = response.data.map((device: any) => { + const domain = device.entity_id.split(".")[0]; + + // Find valid services for this entity's domain + const domainServices = + services.find((service: any) => service.domain === domain)?.services || + []; + + return { + entity_id: device.entity_id, + state: device.state, + friendly_name: device.attributes.friendly_name || "", + valid_services: domainServices, // Add the valid services for this device + attributes: { + valid_states: device.attributes.valid_states || [], + }, + }; + }); + + return devices; + } catch (error) { + console.error("Error fetching devices:", error); + throw error; + } +} + +const devicesCache = new AsyncCache(getAllDevicesRaw); + +export async function getAllDevices() { + try { + const devices = await devicesCache.get(); + return { devices }; + } catch (error) { + return { error }; + } +} + +// -------------------- Existing Functionality -------------------- // + +// Schema for setting the state with service and optional parameters +export const SetDeviceStateParams = z.object({ + entity_id: z.string(), + service: z.string(), // Taking service directly + value: z + .string() + .optional() + .describe( + "The value to set for the service. use this for simple use cases like for setting text, for more complex use cases use params" + ), + params: z + .object({}) + .optional() + .describe( + `This object contains optional parameters for the service. For example, you can pass the brightness, color, or other parameters specific to the service.` + ), // Optional parameters for the service (e.g., brightness, color) +}); +export type SetDeviceStateParams = z.infer; + +// Schema for fuzzy search +export const FuzzySearchParams = z.object({ + query: z.string(), +}); +export type FuzzySearchParams = z.infer; + +// 3. Fuzzy search devices and include valid services +export async function fuzzySearchDevices({ query }: FuzzySearchParams) { + try { + // Fetch all devices with their services + const { devices }: any = await getAllDevices(); + + if (!devices) { + return { error: "No devices data available." }; + } + + const fuseOptions = { + keys: ["friendly_name", "entity_id"], + threshold: 0.3, // Controls the fuzziness, lower value means stricter match + }; + + const fuse = new Fuse(devices, fuseOptions); + const results = fuse.search(query); + + // Get top 2 results + const topMatches = results.slice(0, 2).map((result) => result.item); + + return { matches: topMatches }; + } catch (error) { + console.error("Error performing fuzzy search:", error); + return { error }; + } +} + +// 4. Function to set the state of a device via a service + +// Updated setDeviceState function +export async function setDeviceState({ + entity_id, + service, + value, + params = {}, +}: SetDeviceStateParams) { + try { + const domain = entity_id.split(".")[0]; + + // Fetch valid services for the specific domain + const valid_services = await getServicesForDomain(domain); + + // Ensure valid_services is an object and extract the service keys + const valid_service_keys = valid_services + ? Object.keys(valid_services) + : []; + + // Check if the passed service is valid + if (!valid_service_keys.includes(service)) { + return { + success: false, + message: `Invalid service '${service}' for entity ${entity_id}. Valid services are: ${valid_service_keys.join( + ", " + )}.`, + }; + } + + if (!params && !value) { + return { + success: false, + message: `No value or params provided for service '${service}' for entity ${entity_id}.`, + }; + } + + // Send a POST request to the appropriate service endpoint with optional parameters + const response = await apiClient.post(`/services/${domain}/${service}`, { + entity_id, + value, + ...params, + }); + + return { success: response.status === 200 }; + } catch (error) { + const err = error as AxiosError; + const errMessage = err.response?.data || { message: err.message }; + console.error( + `Error setting state for device ${entity_id}:`, + JSON.stringify(errMessage, null, 2) + ); + return { errMessage }; + } +} + +// Schema for getting device state +export const GetDeviceStateParams = z.object({ + entity_id: z.string(), +}); +export type GetDeviceStateParams = z.infer; + +// Fetch services for a specific domain (e.g., light, switch) +async function getServicesForDomain(domain: string) { + try { + const services = await getAllServices(); + if ("error" in services) throw services.error; + + const domainServices = services.find( + (service: any) => service.domain === domain + ); + return domainServices ? domainServices.services : []; + } catch (error) { + console.error(`Error fetching services for domain ${domain}:`, error); + return []; + } +} + +// Function to get the current state and valid services of a specific device +export async function getDeviceState({ entity_id }: GetDeviceStateParams) { + try { + // Fetch the device state + const response = await apiClient.get(`/states/${entity_id}`); + const device = response.data; + + // Extract the domain from entity_id (e.g., "light", "switch") + const domain = entity_id.split(".")[0]; + + // Fetch services for the specific domain + const valid_services = await getServicesForDomain(domain); + + // Return device state and valid services + return { + entity_id: device.entity_id, + state: device.state, + friendly_name: device.attributes.friendly_name || "", + valid_services, // Return valid services for this device + attributes: { + valid_states: device.attributes.valid_states || [], + }, + }; + } catch (error) { + console.error(`Error fetching state for device ${entity_id}:`, error); + return { + error, + }; + } +} + +// Tools export +export let homeAssistantTools: RunnableToolFunctionWithParse[] = [ + // zodFunction({ + // function: getAllDevices, + // name: "homeAssistantGetAllDevices", + // schema: z.object({}), // No parameters needed + // description: + // "Get a list of all devices with their current states and valid services that can be called.", + // }), + zodFunction({ + function: setDeviceState, + name: "homeAssistantSetDeviceState", + schema: SetDeviceStateParams, + description: `Set the state of a specific device by calling a valid service, such as 'turn_on' or 'turn_off'. + + For simple text fields u can just use the following format too: + + `, + }), + zodFunction({ + function: fuzzySearchDevices, + name: "homeAssistantFuzzySearchDevices", + schema: FuzzySearchParams, + description: + "Search devices by name and return their entity_id, current state, and valid services that can be called to control the device.", + }), +]; + +export const HomeManagerParams = z.object({ + request: z.string().describe("What the user wants to do with which device"), + // device_name: z.string().describe("What the user referred to the device as"), + devices: z + .array(z.string()) + .describe("The vague device names to potentially take action on"), +}); +export type HomeManagerParams = z.infer; + +export async function homeManager( + { request, devices }: HomeManagerParams, + context_message: Message +) { + const allMatches = []; + + for (const device of devices) { + const { matches } = await fuzzySearchDevices({ query: device }); + if (matches?.length) { + allMatches.push(...matches); + } + } + + if (allMatches.length === 0) { + return { + error: `No devices found matching the provided names. Please try again.`, + }; + } + + const response = await ask({ + model: "gpt-4o-mini", + prompt: `You are a home assistant manager. + +---- +${memory_manager_guide("homeassistant-manager")} +---- + + Similar devices were found based on the names provided: + ${JSON.stringify(allMatches)} + + These are the devices that they may actually be referring to: + ${JSON.stringify(allMatches)} + + Read the request carefully and perform the necessary action on only the RELEVANT devices. + `, + message: request, + seed: `home-${context_message.channelId}`, + tools: [ + ...homeAssistantTools, + memory_manager_init(context_message, "homeassistant-manager"), + ], + }); + + return { + response: response.choices[0].message.content, + }; +} diff --git a/tools/index.ts b/tools/index.ts new file mode 100644 index 0000000..a5141f7 --- /dev/null +++ b/tools/index.ts @@ -0,0 +1,511 @@ +import { + RunnableToolFunction, + RunnableToolFunctionWithParse, +} from "openai/lib/RunnableFunction.mjs"; +import { JSONSchema } from "openai/lib/jsonschema.mjs"; +import { z, ZodSchema } from "zod"; +import zodToJsonSchema from "zod-to-json-schema"; +import { evaluate } from "mathjs"; + +import { + YoutubeDownloaderParams, + YoutubeTranscriptParams, + get_download_link, + get_youtube_video_data, +} from "./youtube"; +import { + SendGeneralMessageParams, + SendMessageParams, + send_general_message, + send_message_to, +} from "./messenger"; +import { + ChartParams, + PythonCodeParams, + RunPythonCommandParams, + chart, + code_interpreter, + run_command_in_code_interpreter_env, +} from "./python-interpreter"; +import { meme_maker, MemeMakerParams } from "./meme-maker"; +import { getPeriodTools } from "./period"; +import { linkManager, LinkManagerParams } from "./linkwarden"; +import { search_chat, SearchChatParams } from "./chat-search"; +import { getTotalCompletionTokensForModel } from "../usage"; +import { + scrape_and_convert_to_markdown, + ScrapeAndConvertToMarkdownParams, +} from "./scrape"; +import { calendarManager, CalendarManagerParams } from "./calender"; +import { remindersManager, RemindersManagerParams } from "./reminders"; +import { notesManager, NotesManagerParams, webdav_tools } from "./notes"; +import { service_checker, ServiceCheckerParams } from "./status"; +import { + upload_file, + UploadFileParams, + get_file_list, + GetFileListParams, +} from "./files"; +// Removed import of createContextMessage since it's not used here +import { Message } from "../interfaces/message"; +import { rolePermissions, userConfigs } from "../config"; // <-- Added import +import { search_user, SearchUserParams } from "./search-user"; +import { ResendParams, send_email } from "./resend"; +import { homeManager, HomeManagerParams } from "./home"; +import { event_manager, EventManagerSchema } from "./events"; +import { actionManager, ActionManagerParamsSchema } from "./actions"; +import { search_whatsapp_contacts, SearchContactsParams } from "./whatsapp"; +import { memory_manager_init } from "./memory-manager"; +import { communication_manager_tool } from "./communication"; +import { send_sys_log } from "../interfaces/log"; + +// get time function +const GetTimeParams = z.object({}); +type GetTimeParams = z.infer; +async function get_date_time({}: GetTimeParams) { + return { response: new Date().toLocaleString() }; +} + +// calculator function +const CalculatorParams = z.object({ + expression: z.string().describe("mathjs expression"), +}); +type CalculatorParams = z.infer; +async function calculator({ expression }: CalculatorParams) { + return { response: evaluate(expression) }; +} + +// run bash command function and return all output success/errors both +const RunBashCommandParams = z.object({ + command: z.string(), +}); +type RunBashCommandParams = z.infer; +async function run_bash_command({ command }: RunBashCommandParams) { + console.log("running command: " + command); + const { exec } = await import("child_process"); + return (await new Promise((resolve) => { + exec(command, (error, stdout, stderr) => { + console.log("stdout: " + stdout); + console.log("stderr: " + stderr); + if (error !== null) { + console.log("exec error: " + error); + } + resolve({ stdout, stderr, error }); + }); + })) as { stdout: string; stderr: string; error: any }; +} + +// exit process +const ExitProcessParams = z.object({}); +type ExitProcessParams = z.infer; +async function restart_self({}: ExitProcessParams, context_message: Message) { + await Promise.all([ + send_sys_log("Restarting myself"), + context_message.send({ + content: "Restarting myself", + }), + context_message.send({ + content: "---setting this point as the start---", + }), + ]); + return { response: process.exit(0) }; +} + +function delay(ms: number) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +// get total tokens used by a model +const GetTotalTokensParams = z.object({ + model: z.string(), + from: z.string(), + to: z.string(), +}); + +type GetTotalTokensParams = z.infer; + +async function get_total_tokens({ model, from, to }: GetTotalTokensParams) { + return { + response: getTotalCompletionTokensForModel(model, from, to), + }; +} + +export function getTools( + username: string, + context_message: Message, + manager_id?: string +) { + const userRoles = context_message.getUserRoles(); + + // Aggregate permissions from all roles + const userPermissions = new Set(); + userRoles.forEach((role) => { + const permissions = rolePermissions[role]; + if (permissions) { + permissions.forEach((perm) => userPermissions.add(perm)); + } + }); + + // Helper function to check if the user has access to a tool + function hasAccess(toolName: string): boolean { + if (toolName === "periodTools") { + return userPermissions.has("periodUser"); + } + return userPermissions.has("*") || userPermissions.has(toolName); + } + + // Define all tools with their names + const allTools: { + name: string; + tool: RunnableToolFunction | RunnableToolFunction[]; + }[] = [ + { + name: "calculator", + tool: zodFunction({ + function: calculator, + schema: CalculatorParams, + description: "Evaluate math expression", + }), + }, + { + name: "getTime", + tool: zodFunction({ + function: get_date_time, + schema: GetTimeParams, + description: "Get current date and time", + }), + }, + { + name: "search_user_ids", + tool: zodFunction({ + function: (args) => search_user(args, context_message), + name: "search_user_ids", + schema: SearchUserParams, + description: `Search and get user's details. Use this only when required.`, + }), + }, + + // Computer nerd tools + + // { + // name: "search_whatsapp_contacts", + // tool: zodFunction({ + // function: search_whatsapp_contacts, + // schema: SearchContactsParams, + // description: `Search for contacts in user's whatsapp account. Use this to get whatsapp user_id of any user. + // Note: Confirm from the user before sending any messages to the contacts found using this search. + // `, + // }), + // }, + /* { + name: "scrapeWeb", + tool: zodFunction({ + function: scrape_and_convert_to_markdown, + schema: ScrapeAndConvertToMarkdownParams, + name: "scrape_web", + description: `Get data from a webpage.`, + }), + }, + { + name: "uploadFile", + tool: zodFunction({ + function: upload_file, + schema: UploadFileParams, + description: `Upload a LOCAL file to a MinIO bucket and return its public URL. + +Note: +- The filePath should be a local file path in the /tmp directory. +- If you want to re-upload a file from the internet, you can download it using run_shell_command to a /tmp directory and then upload it. + +Use cases: +- You can use this to share files from inside the code interpreter using the /tmp file path. +- You can use this to share files that only you have access to, like temporary files or discord files. +- You can use this when the user explicitly asks for a file to be shared with them or wants to download a file.`, + }), + }, + { + name: "getFileList", + tool: zodFunction({ + function: get_file_list, + schema: GetFileListParams, + description: `Get the list of public URLs for all files in the MinIO bucket`, + }), + }, + { + name: "getYouTubeVideoData", + tool: zodFunction({ + function: get_youtube_video_data, + schema: YoutubeTranscriptParams as any, + description: + "Get YouTube video data. Use this only when sent a YouTube URL. Do not use this for YouTube search.", + }), + }, + { + name: "getDownloadLink", + tool: zodFunction({ + function: get_download_link as any, + schema: YoutubeDownloaderParams, + description: `Get download link for YouTube links. +Also, always hide the length of links that are too long by formatting them with markdown. +For any site other than YouTube, use code interpreter to scrape the download link. + +If the user wants the file and not just the link: +You can use the direct link you get from this to download the media inside code interpreter and then share the downloaded files using the send message tool. +Make sure that the file size is within discord limits.`, + }), + }, + { + name: "codeInterpreter", + tool: zodFunction({ + function: (args) => code_interpreter(args, context_message), + name: "code_interpreter", + schema: PythonCodeParams, + description: `Primary Function: Run Python code in an isolated environment. +Key Libraries: pandas for data analysis, matplotlib for visualization. +Use Cases: Data analysis, plotting, image/video processing using ffmpeg for video, complex calculations, and attachment analysis. +You can also use this to try to scrape and get download links from non-YouTube sites. + +File sharing: +To share a file with a user from inside code interpreter, you can save the file to the /tmp/ directory and then use the send message tool to send the file to the user by using the full path of the file, including the /tmp part in the path. + +Notes: +Import necessary libraries; retry if issues arise. +For web scraping, process data to stay within a 10,000 token limit. +Use run_shell_command to check or install dependencies. +Try to fix any errors that are returned at least once before sending to the user, especially syntax/type errors.`, + }), + }, + { + name: "runShellCommand", + tool: zodFunction({ + function: (args) => + run_command_in_code_interpreter_env(args, context_message), + name: "run_shell_command", + schema: RunPythonCommandParams, + description: `Run bash command. Use this to install any needed dependencies.`, + }), + }, */ + + // { + // name: "generateChart", + // tool: zodFunction({ + // function: chart, + // name: "generate_chart", + // schema: ChartParams, + // description: `Generate chart PNG image URL using quickchart.io`, + // }), + // }, + // { + // name: "memeOrCatMaker", + // tool: zodFunction({ + // function: meme_maker, + // name: "meme_or_cat_maker", + // schema: MemeMakerParams, + // description: `Generate meme image URL using memegen.link OR generate cat image URL using cataas.com + + // Just provide the info in the query, and it will generate the URL for you. + // This can include any memegen.link or cataas.com specific parameters. + // Make sure to give as many details as you can about what the user wants. + // Also, make sure to send the images and memes as files to the user using the send message tool unless explicitly asked to send the URL.`, + // }), + // }, + // { + // name: "sendMessageToChannel", + // tool: zodFunction({ + // function: (args) => send_general_message(args, context_message), + // name: "send_message_to_channel", + // schema: SendGeneralMessageParams, + // description: `Send message to the current Discord channel. + // You can also use this for reminders or other scheduled messages by calculating the delay from the current time. + // If the user does not specify a time for a reminder, think of one based on the task. + // If no channel ID is provided, the message will be sent to the user you are currently chatting with.`, + // }), + // }, + // { + // name: "searchChat", + // tool: zodFunction({ + // function: (args) => search_chat(args, context_message), + // name: "search_chat", + // schema: SearchChatParams, + // description: `Search for messages in the current channel based on query parameters. + // This will search the last 100 (configurable by setting the limit parameter) messages in the channel. + // Set user_only parameter to true if you want to search only the user's messages.`, + // }), + // }, + { + name: "serviceChecker", + tool: zodFunction({ + function: service_checker, + name: "service_checker", + schema: ServiceCheckerParams, + description: `Check the status of a service by querying the status page of the service. Use this when the user asks if something is up or down in the context of a service.`, + }), + }, + // { + // name: "getTotalTokens", + // tool: zodFunction({ + // function: get_total_tokens, + // name: "get_total_tokens", + // schema: GetTotalTokensParams, + // description: `Get total tokens used by a model in a date range + + // The pricing as of 2024 is: + // gpt-4o: + // $5.00 / 1M prompt tokens + // $15.00 / 1M completion tokens + + // gpt-4o-mini: + // $0.150 / 1M prompt tokens + // $0.600 / 1M completion tokens + + // Use calculator to make the math calculations.`, + // }), + // }, + { + name: "communicationsManagerTool", + tool: communication_manager_tool(context_message), + }, + { + name: "calendarManagerTool", + tool: zodFunction({ + function: (args) => calendarManager(args, context_message), + name: "calendar_manager", + schema: CalendarManagerParams, + description: `Manage calendar events using user's Calendar. + You can just forward the user's request to this tool and it will handle the rest.`, + }), + }, + { + name: "remindersManagerTools", + tool: zodFunction({ + function: (args) => remindersManager(args, context_message), + name: "reminders_manager", + schema: RemindersManagerParams, + description: `Manage reminders using user's reminders. + You can just forward the user's request to this tool and it will handle the rest.`, + }), + }, + { + name: "homeAssistantManagerTool", + tool: zodFunction({ + function: (args) => homeManager(args, context_message), + name: "home_assistant_manager", + schema: HomeManagerParams, + description: `Manage home assistant devices and services in natural language. + Give as much details as possible to get the best results. + Especially what devices that the user named and what action they want to perform on them. + `, + }), + }, + { + name: "notesManagerTool", + tool: zodFunction({ + function: (args) => notesManager(args, context_message), + name: "notes_manager", + schema: NotesManagerParams, + description: `Manage notes using user's notes. + + You can just forward the user's request verbatim (or by adding more clarity) to this tool and it will handle the rest. + + When to use: + if user talks about any notes, lists, journal, gym entry, standup, personal journal, etc. + `, + }), + }, + { + name: "linkManagerTool", + tool: zodFunction({ + function: (args) => linkManager(args, context_message), + name: "link_manager", + schema: LinkManagerParams, + description: `Manage links using LinkWarden. + You can just forward the user's request to this tool and it will handle the rest. + `, + }), + }, + { + name: "actionsManagerTool", + tool: zodFunction({ + function: (args) => actionManager(args, context_message), + name: "actions_manager", + schema: ActionManagerParamsSchema, + description: `Manage scheduled actions using the Actions Manager. + + Forward user requests to create, update, retrieve, or remove actions. + + You can use this for when a user wants you to do something at a specific time or after a specific time.`, + }), + }, + { + name: "eventsManagerTool", + tool: zodFunction({ + function: (args) => event_manager(args, context_message), + name: "events_manager", + schema: EventManagerSchema, + description: `Manage events using the Events Manager. + + Forward user requests to create, update, retrieve, or remove events. + + When to use: + if user wants to create some automation based on some event.`, + }), + }, + { + name: "restart", + tool: zodFunction({ + function: (args) => restart_self(args, context_message), + name: "restart_self", + schema: ExitProcessParams, + description: + "Restart yourself. do this only when the user explicitly asks you to restart yourself.", + }), + }, + // { + // name: "eventTools", + // tool: event_tools(context_message), + // }, + // Period tools + { + name: "periodTools", + tool: getPeriodTools(context_message), + }, + ]; + + const manager_tools = manager_id + ? [memory_manager_init(context_message, manager_id)] + : []; + + // Filter tools based on user permissions + const tools = allTools + .filter(({ name }) => hasAccess(name)) + .flatMap(({ tool }) => (Array.isArray(tool) ? tool : [tool])) + .concat(manager_tools); + + return tools; +} + +export function zodFunction({ + function: fn, + schema, + description = "", + name, +}: { + function: (args: T) => Promise | object; + schema: ZodSchema; + description?: string; + name?: string; +}): RunnableToolFunctionWithParse { + return { + type: "function", + function: { + function: fn, + name: name ?? fn.name, + description: description, + parameters: zodToJsonSchema(schema) as JSONSchema, + parse(input: string): T { + const obj = JSON.parse(input); + return schema.parse(obj); + }, + }, + }; +} diff --git a/tools/linkwarden.ts b/tools/linkwarden.ts new file mode 100644 index 0000000..5b4c02e --- /dev/null +++ b/tools/linkwarden.ts @@ -0,0 +1,426 @@ +import axios from "axios"; +import { z } from "zod"; +import { zodFunction } from "."; +import { RunnableToolFunction } from "openai/lib/RunnableFunction.mjs"; +import { ask } from "./ask"; +import { Message } from "../interfaces/message"; +import { memory_manager_guide, memory_manager_init } from "./memory-manager"; + +const apiClient = axios.create({ + baseURL: "https://link.raj.how/api/v1", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${process.env.LINKWARDEN_API_KEY}`, + }, +}); + +// Schemas for each function's parameters +export const ArchivedFileParams = z.object({ + id: z.string(), + format: z.string().optional(), +}); +export type ArchivedFileParams = z.infer; + +export const TagParams = z.object({ + id: z.string(), +}); +export type TagParams = z.infer; + +export const TagUpdateParams = z.object({ + id: z.string(), + name: z.string().optional(), + color: z.string().optional(), +}); +export type TagUpdateParams = z.infer; + +export const CollectionParams = z.object({ + id: z.string(), +}); +export type CollectionParams = z.infer; + +export const CollectionLinksParams = z.object({ + collectionId: z.string(), + tag: z.string().optional(), + sortBy: z.string().optional(), + limit: z.number().optional(), +}); +export type CollectionLinksParams = z.infer; + +export const ProfileParams = z.object({ + id: z.string(), +}); +export type ProfileParams = z.infer; + +export const MigrationParams = z.object({ + data: z.string(), +}); +export type MigrationParams = z.infer; + +export const LinksParams = z.object({ + collectionId: z.string().optional(), + tag: z.string().optional(), + sortBy: z.string().optional(), + limit: z.number().optional(), +}); +export type LinksParams = z.infer; + +export const LinkParams = z.object({ + id: z.string(), +}); +export type LinkParams = z.infer; + +export const LinkUpdateParams = z.object({ + id: z.string(), + title: z.string().optional(), + url: z.string().optional(), + description: z.string().optional(), + tagIds: z.array(z.string()).optional(), +}); +export type LinkUpdateParams = z.infer; + +export const ProfilePhotoParams = z.object({ + id: z.string(), +}); +export type ProfilePhotoParams = z.infer; + +// Functions +export async function getArchivedFile({ id, format }: ArchivedFileParams) { + try { + const response = await apiClient.get(`/archives/${id}`, { + params: { format }, + }); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function getAllTags() { + try { + const response = await apiClient.get("/tags"); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function updateTag({ id, name, color }: TagUpdateParams) { + try { + const response = await apiClient.put(`/tags/${id}`, { name, color }); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function deleteTag({ id }: TagParams) { + try { + const response = await apiClient.delete(`/tags/${id}`); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function getPublicCollectionInfo({ id }: CollectionParams) { + try { + const response = await apiClient.get(`/public/collections/${id}`); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function getLinksUnderPublicCollection({ + collectionId, + tag, + sortBy, + limit, +}: CollectionLinksParams) { + try { + const response = await apiClient.get("/public/collections/links", { + params: { collectionId, tag, sortBy, limit }, + }); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function getSingleLinkUnderPublicCollection({ id }: LinkParams) { + try { + const response = await apiClient.get(`/public/links/${id}`); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function getPublicProfileInfo({ id }: ProfileParams) { + try { + const response = await apiClient.get(`/public/users/${id}`); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function importData({ data }: MigrationParams) { + try { + const response = await apiClient.post("/migration", { data }); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function exportData({ data }: MigrationParams) { + try { + const response = await apiClient.get("/migration", { params: { data } }); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function getLinks({ + collectionId, + tag, + sortBy, + limit, +}: LinksParams) { + try { + const response = await apiClient.get("/links", { + params: { collectionId, tag, sortBy, limit }, + }); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function getLink({ id }: LinkParams) { + try { + const response = await apiClient.get(`/links/${id}`); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +// Schema for adding a link +export const AddLinkParams = z.object({ + url: z.string(), + name: z.string(), + type: z.string(), + tags: z.array( + z.object({ + name: z.string(), + }) + ), + collection: z.object({ + id: z.number().default(8).optional(), + }), +}); +export type AddLinkParams = z.infer; + +// Function to add a link +export async function addLink(params: AddLinkParams) { + try { + const response = await apiClient.post("/links", params); + return response.data; + } catch (error) { + console.error(error); + return `Error: ${error}`; + } +} + +export async function updateLink({ + id, + title, + url, + description, + tagIds, +}: LinkUpdateParams) { + try { + const response = await apiClient.put(`/links/${id}`, { + title, + url, + description, + tagIds, + }); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function deleteLink({ id }: LinkParams) { + try { + const response = await apiClient.delete(`/links/${id}`); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function triggerArchiveForLink({ id }: LinkParams) { + try { + const response = await apiClient.put(`/links/${id}/archive`); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function getDashboardData() { + try { + const response = await apiClient.get("/dashboard"); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function getCollections() { + try { + const response = await apiClient.get("/collections"); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export async function getProfilePhoto({ id }: ProfilePhotoParams) { + try { + const response = await apiClient.get(`/avatar/${id}`); + return response.data; + } catch (error) { + return `Error: ${error}`; + } +} + +export let link_tools: RunnableToolFunction[] = [ + zodFunction({ + function: getAllTags, + name: "linkwardenGetAllTags", + schema: z.object({}), + description: "Get all tags for the user.", + }), + zodFunction({ + function: updateTag, + name: "linkwardenUpdateTag", + schema: TagUpdateParams, + description: "Update a tag.", + }), + zodFunction({ + function: deleteTag, + name: "linkwardenDeleteTag", + schema: TagParams, + description: "Delete a tag.", + }), + zodFunction({ + function: getPublicCollectionInfo, + name: "linkwardenGetPublicCollectionInfo", + schema: CollectionParams, + description: "Get public collection info.", + }), + zodFunction({ + function: getLinksUnderPublicCollection, + name: "linkwardenGetLinksUnderPublicCollection", + schema: CollectionLinksParams, + description: "Get links under a public collection.", + }), + zodFunction({ + function: getSingleLinkUnderPublicCollection, + name: "linkwardenGetSingleLinkUnderPublicCollection", + schema: LinkParams, + description: "Get a single link under a public collection.", + }), + zodFunction({ + function: getPublicProfileInfo, + name: "linkwardenGetPublicProfileInfo", + schema: ProfileParams, + description: "Get public profile info.", + }), + zodFunction({ + function: getLinks, + name: "linkwardenGetLinks", + schema: LinksParams, + description: "Get links under a collection.", + }), + zodFunction({ + function: getLink, + name: "linkwardenGetLink", + schema: LinkParams, + description: "Get a single link under a collection.", + }), + zodFunction({ + function: updateLink, + name: "linkwardenUpdateLink", + schema: LinkUpdateParams, + description: "Update a link.", + }), + zodFunction({ + function: addLink, + name: "linkwardenAddLink", + schema: AddLinkParams, + description: + "Add a link (default to 'Anya' collection with id=8 if not specified).", + }), + zodFunction({ + function: deleteLink, + name: "linkwardenDeleteLink", + schema: LinkParams, + description: "Delete a link.", + }), + zodFunction({ + function: triggerArchiveForLink, + name: "linkwardenTriggerArchiveForLink", + schema: LinkParams, + description: "Trigger archive for a link.", + }), + zodFunction({ + function: getDashboardData, + name: "linkwardenGetDashboardData", + schema: z.object({}), + description: "Get dashboard data.", + }), + zodFunction({ + function: getCollections, + name: "linkwardenGetCollections", + schema: z.object({}), + description: "Get all collections for the user.", + }), +]; + +export const LinkManagerParams = z.object({ + request: z + .string() + .describe("User's request regarding links, tags, or collections."), +}); +export type LinkManagerParams = z.infer; + +export async function linkManager( + { request }: LinkManagerParams, + context_message: Message +) { + const response = await ask({ + model: "gpt-4o-mini", + prompt: `You are a Linkwarden manager. + +Your job is to understand the user's request and manage links, tags, or collections using the available tools. + +---- +${memory_manager_guide("links_manager")} +---- + `, + message: request, + seed: "link-${context_message.channelId}", + tools: link_tools.concat( + memory_manager_init(context_message, "links_manager") + ) as any, + }); + + return { response }; +} diff --git a/tools/meme-maker.ts b/tools/meme-maker.ts new file mode 100644 index 0000000..9e4f311 --- /dev/null +++ b/tools/meme-maker.ts @@ -0,0 +1,65 @@ +import OpenAI from "openai"; +import { z } from "zod"; + +// get meta data from url +export const MemeMakerParams = z.object({ + query: z.string(), +}); + +export type MemeMakerParams = z.infer; + +const ai_token = process.env.OPENAI_API_KEY?.trim(); +const openai = new OpenAI({ + apiKey: ai_token, +}); + +const mememaker_swagger = + '{"openapi":"3.0.3","info":{"title":"Memegen.link","version":"11.0","description":"\n## Quickstart\n\nFetch the list of templates:\n\n```\n$ http GET https://api.memegen.link/templates\n\n[\n {\n "id": "aag",\n "name": "Ancient Aliens Guy",\n "lines": 2,\n "overlays": 0,\n "styles": [],\n "blank": "https://api.memegen.link/images/aag.png",\n "example": {\n "text": [\n "",\n "aliens"\n ],\n "url": "https://api.memegen.link/images/aag/_/aliens.png"\n },\n "source": "http://knowyourmeme.com/memes/ancient-aliens",\n },\n ...\n]\n```\n\nAdd text to create a meme:\n\n```\n$ http POST https://api.memegen.link/images template_id=aag "text[]=foo" "text[]=bar"\n\n{\n "url": "https://api.memegen.link/images/aag/foo/bar.png"\n}\n```\n\nView the image: \n\n## Links\n","license":{"name":"View the license","url":"https://github.com/jacebrowning/memegen/blob/main/LICENSE.txt"},"contact":{"name":"support","email":"support@maketested.com"}},"paths":{"/auth":{"post":{"operationId":"post~Clients.validate","summary":"Validate your API key","tags":["Clients"],"responses":{"401":{"content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","title":"Error"}}}}},"description":"Your API key is invalid"},"200":{"content":{"application/json":{"schema":{"type":"object","properties":{"email":{"type":"string","title":"Email"},"image_access":{"type":"boolean","title":"Image_Access"},"search_access":{"type":"boolean","title":"Search_Access"},"created":{"type":"string","format":"date-time","title":"Created"},"modified":{"type":"string","format":"date-time","title":"Modified"}}}}},"description":"Your API key is valid"}}}},"/images/preview.jpg":{"get":{"operationId":"get~Clients.preview","summary":"Display a preview of a custom meme","tags":["Clients"],"parameters":[{"name":"layout","schema":{"type":"string"},"description":"Text position: `default` or `top`","in":"query"},{"name":"template","schema":{"type":"string"},"description":"Template ID, URL, or custom background","in":"query"},{"name":"style","schema":{"type":"string"},"description":"Style name or custom overlay","in":"query"},{"name":"text[]","schema":{"type":"string"},"description":"Lines of text to render","in":"query"}],"responses":{"200":{"content":{"image/jpeg":{"schema":{"type":"string","format":"byte"}}},"description":"Successfully displayed a custom meme"}}}},"/fonts":{"get":{"operationId":"get~Fonts.index","summary":"List available fonts","tags":["Fonts"],"responses":{"200":{"content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"filename":{"type":"string","title":"Filename"},"id":{"type":"string","title":"Id"},"alias":{"type":"string","title":"Alias"}}}}}},"description":"Successfully returned a list of fonts"}}}},"/images/custom":{"get":{"operationId":"get~Images.index_custom","summary":"List popular custom memes","tags":["Images"],"parameters":[{"name":"filter","schema":{"type":"string"},"description":"Part of the meme\'s text to match","in":"query"},{"name":"safe","schema":{"type":"boolean"},"description":"Exclude NSFW results","in":"query"}],"responses":{"200":{"content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"url":{"type":"string","title":"Url"}}}}}},"description":"Successfully returned a list of custom memes"}}},"post":{"operationId":"post~Images.create_custom","summary":"Create a meme from any image","tags":["Images"],"responses":{"201":{"content":{"application/json":{"schema":{"type":"object","properties":{"url":{"type":"string","title":"Url"}}}}},"description":"Successfully created a meme from a custom image"}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"background":{"type":"string","title":"Background"},"style":{"type":"string","title":"Style"},"text":{"type":"array","items":{"type":"string"},"title":"Text"},"layout":{"type":"string","title":"Layout"},"font":{"type":"string","title":"Font"},"extension":{"type":"string","title":"Extension"},"redirect":{"type":"boolean","title":"Redirect"}}}}}}}},"/images":{"get":{"operationId":"get~Images.index","summary":"List example memes","tags":["Images"],"parameters":[{"name":"filter","schema":{"type":"string"},"description":"Part of the template name or example to match","in":"query"}],"responses":{"200":{"content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"url":{"type":"string","title":"Url"},"template":{"type":"string","title":"Template"}}}}}},"description":"Successfully returned a list of example memes"}}},"post":{"operationId":"post~Images.create","summary":"Create a meme from a template","tags":["Images"],"responses":{"404":{"content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","title":"Error"}}}}},"description":"Specified "template_id" does not exist"},"400":{"content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","title":"Error"}}}}},"description":"Required "template_id" missing in request body"},"201":{"content":{"application/json":{"schema":{"type":"object","properties":{"url":{"type":"string","title":"Url"}}}}},"description":"Successfully created a meme"}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"template_id":{"type":"string","title":"Template_Id"},"style":{"type":"array","items":{"type":"string"},"title":"Style"},"text":{"type":"array","items":{"type":"string"},"title":"Text"},"layout":{"type":"string","title":"Layout"},"font":{"type":"string","title":"Font"},"extension":{"type":"string","title":"Extension"},"redirect":{"type":"boolean","title":"Redirect"}}}}}}}},"/images/automatic":{"post":{"operationId":"post~Images.create_automatic","summary":"Create a meme from word or phrase","tags":["Images"],"responses":{"400":{"content":{"application/json":{"schema":{"type":"object","properties":{"error":{"type":"string","title":"Error"}}}}},"description":"Required "text" missing in request body"},"201":{"content":{"application/json":{"schema":{"type":"object","properties":{"url":{"type":"string","title":"Url"}}}}},"description":"Successfully created a meme"}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"text":{"type":"string","title":"Text"},"safe":{"type":"boolean","title":"Safe"},"redirect":{"type":"boolean","title":"Redirect"}}}}}}}},"/templates/custom":{"post":{"operationId":"post~Templates.custom","summary":"Create a meme from any image","tags":["Templates"],"responses":{"201":{"content":{"application/json":{"schema":{"type":"object","properties":{"url":{"type":"string","title":"Url"}}}}},"description":"Successfully created a meme from a custom image"}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"background":{"type":"string","title":"Background"},"style":{"type":"string","title":"Style"},"text":{"type":"array","items":{"type":"string"},"title":"Text"},"layout":{"type":"string","title":"Layout"},"font":{"type":"string","title":"Font"},"extension":{"type":"string","title":"Extension"},"redirect":{"type":"boolean","title":"Redirect"}}}}}}}},"/templates":{"get":{"operationId":"get~Templates.index","summary":"List all templates","tags":["Templates"],"parameters":[{"name":"filter","schema":{"type":"string"},"description":"Part of the name, keyword, or example to match","in":"query"},{"name":"animated","schema":{"type":"boolean"},"description":"Limit results to templates supporting animation","in":"query"}],"responses":{"200":{"content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string","title":"Id"},"name":{"type":"string","title":"Name"},"lines":{"type":"integer","format":"int32","title":"Lines"},"overlays":{"type":"integer","format":"int32","title":"Overlays"},"styles":{"type":"array","items":{"type":"string"},"title":"Styles"},"blank":{"type":"string","title":"Blank"},"example":{"type":"object","title":"Example","properties":{"text":{"type":"array","items":{"type":"string"},"title":"Text"},"url":{"type":"string","title":"Url"}}},"source":{"type":"string","title":"Source"}}}}}},"description":"Successfully returned a list of all templates"}}}},"/fonts/{id}":{"get":{"operationId":"get~Fonts.detail","summary":"View a specific font","tags":["Fonts"],"parameters":[{"name":"id","schema":{"type":"string"},"description":"ID of a font","required":true,"in":"path"}],"responses":{"404":{"content":{"*/*":{"schema":{"type":"string"}}},"description":"Font not found"},"200":{"content":{"application/json":{"schema":{"type":"object","properties":{"filename":{"type":"string","title":"Filename"},"id":{"type":"string","title":"Id"},"alias":{"type":"string","title":"Alias"}}}}},"description":"Successfully returned a specific font"}}}},"/templates/{id}":{"post":{"operationId":"post~Templates.build","summary":"Create a meme from a template","tags":["Templates"],"parameters":[{"name":"id","schema":{"type":"string"},"description":"ID of a meme template","required":true,"in":"path"}],"responses":{"201":{"content":{"application/json":{"schema":{"type":"object","properties":{"url":{"type":"string","title":"Url"}}}}},"description":"Successfully created a meme from a template"}},"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"style":{"type":"array","items":{"type":"string"},"title":"Style"},"text":{"type":"array","items":{"type":"string"},"title":"Text"},"layout":{"type":"string","title":"Layout"},"font":{"type":"string","title":"Font"},"extension":{"type":"string","title":"Extension"},"redirect":{"type":"boolean","title":"Redirect"}}}}}}},"get":{"operationId":"get~Templates.detail","summary":"View a specific template","tags":["Templates"],"parameters":[{"name":"id","schema":{"type":"string"},"description":"ID of a meme template","required":true,"in":"path"}],"responses":{"404":{"content":{"*/*":{"schema":{"type":"string"}}},"description":"Template not found"},"200":{"content":{"application/json":{"schema":{"type":"object","properties":{"id":{"type":"string","title":"Id"},"name":{"type":"string","title":"Name"},"lines":{"type":"integer","format":"int32","title":"Lines"},"overlays":{"type":"integer","format":"int32","title":"Overlays"},"styles":{"type":"array","items":{"type":"string"},"title":"Styles"},"blank":{"type":"string","title":"Blank"},"example":{"type":"object","title":"Example","properties":{"text":{"type":"array","items":{"type":"string"},"title":"Text"},"url":{"type":"string","title":"Url"}}},"source":{"type":"string","title":"Source"}}}}},"description":"Successfully returned a specific template"}}}},"/{template_id}":{"get":{"operationId":"get~Shortcuts.legacy_example_image","summary":"Redirect to an example image","tags":["Shortcuts"],"parameters":[{"name":"template_id","schema":{"type":"string"},"description":"ID of a meme template","required":true,"in":"path"}],"responses":{"404":{"content":{"text/html":{"schema":{"type":"string"}}},"description":"Template not found"},"302":{"content":{"image/*":{"schema":{"type":"string","format":"byte"}}},"description":"Successfully redirected to an example image"}}}},"/images/{template_filename}":{"get":{"operationId":"get~Images.detail_blank","summary":"Display a template background","tags":["Images"],"parameters":[{"name":"template_filename","schema":{"type":"string"},"description":"Template ID and image format: `.`","required":true,"in":"path"}],"responses":{"422":{"content":{"image/*":{"schema":{"type":"string","format":"byte"}}},"description":"Invalid style for template or no image URL specified for custom template"},"415":{"content":{"image/*":{"schema":{"type":"string","format":"byte"}}},"description":"Unable to download image URL"},"404":{"content":{"image/*":{"schema":{"type":"string","format":"byte"}}},"description":"Template not found"},"200":{"content":{"image/*":{"schema":{"type":"string","format":"byte"}}},"description":"Successfully displayed a template background"}}}},"/images/{template_id}/{text_filepath}":{"get":{"operationId":"get~Images.detail_text","summary":"Display a custom meme","tags":["Images"],"parameters":[{"name":"template_id","schema":{"type":"string"},"description":"ID of a meme template","required":true,"in":"path"},{"name":"text_filepath","schema":{"type":"string"},"description":"Lines of text and image format: `/.`","required":true,"in":"path"}],"responses":{"422":{"content":{"image/*":{"schema":{"type":"string","format":"byte"}}},"description":"Invalid style for template or no image URL specified for custom template"},"415":{"content":{"image/*":{"schema":{"type":"string","format":"byte"}}},"description":"Unable to download image URL"},"414":{"content":{"image/*":{"schema":{"type":"string","format":"byte"}}},"description":"Custom text too long (length >200)"},"404":{"content":{"image/*":{"schema":{"type":"string","format":"byte"}}},"description":"Template not found"},"200":{"content":{"image/*":{"schema":{"type":"string","format":"byte"}}},"description":"Successfully displayed a custom meme"}}}},"/images/{template_id}/{text_paths}":{"get":{"operationId":"get~Shortcuts.custom_path","summary":"Redirect to a custom image","tags":["Shortcuts"],"parameters":[{"name":"template_id","schema":{"type":"string"},"description":"ID of a meme template","required":true,"in":"path"},{"name":"text_paths","schema":{"type":"string"},"description":"Lines of text: `/`","required":true,"in":"path"}],"responses":{"302":{"content":{"image/*":{"schema":{"type":"string","format":"byte"}}},"description":"Successfully redirected to a custom image"}}}},"/{template_id}/{text_paths}":{"get":{"operationId":"get~Shortcuts.legacy_custom_image","summary":"Redirect to a custom image","tags":["Shortcuts"],"parameters":[{"name":"template_id","schema":{"type":"string"},"description":"ID of a meme template","required":true,"in":"path"},{"name":"text_paths","schema":{"type":"string"},"description":"Lines of text: `/`","required":true,"in":"path"}],"responses":{"404":{"content":{"text/html":{"schema":{"type":"string"}}},"description":"Template not found"},"302":{"content":{"image/*":{"schema":{"type":"string","format":"byte"}}},"description":"Successfully redirected to a custom image"}}}},"/images/{template_id}":{"get":{"operationId":"get~Shortcuts.example_path","summary":"Redirect to an example image","tags":["Shortcuts"],"parameters":[{"name":"template_id","schema":{"type":"string"},"description":"ID of a meme template","required":true,"in":"path"}],"responses":{"501":{"content":{"text/html":{"schema":{"type":"string"}}},"description":"Template not fully implemented"},"404":{"content":{"text/html":{"schema":{"type":"string"}}},"description":"Template not found"},"302":{"content":{"image/*":{"schema":{"type":"string","format":"byte"}}},"description":"Successfully redirected to an example image"}}}}},"tags":[{"name":"Clients"},{"name":"Fonts"},{"name":"Images"},{"name":"Templates"},{"name":"Shortcuts"}],"servers":[],"security":[{"ApiKeyAuth":[]}],"components":{"securitySchemes":{"ApiKeyAuth":{"type":"apiKey","name":"X-API-KEY","in":"header"}}}}'; + +const cat_swagger = + '{"openapi":"3.0.3","info":{"version":"1.0.0","title":"Cat as a service (CATAAS)","description":"Cat as a service (CATAAS) is a REST API to spread peace and love (or not) thanks to cats."},"servers":[{"url":"https://cataas.com"}],"tags":[{"name":"Cats","description":"Cataas API"},{"name":"API","description":"Public API"},{"name":"Security","description":"Security"},{"name":"Admin","description":"Admin API"}],"components":{"securitySchemes":{"jwt":{"type":"http","scheme":"bearer","bearerFormat":"JWT"}},"schemas":{"AdminCat":{"required":["file","tags","validated"],"type":"object","properties":{"_id":{"type":"string"},"validated":{"type":"boolean"},"file":{"type":"string"},"mimetype":{"type":"string"},"size":{"type":"number"},"tags":{"type":"array","items":{"type":"string"},"default":[]},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}},"Cat":{"required":["file","tags"],"type":"object","properties":{"_id":{"type":"string"},"mimetype":{"type":"string"},"size":{"type":"number"},"tags":{"type":"array","items":{"type":"string"},"default":[]}}},"EditCat":{"required":["tags"],"type":"object","properties":{"tags":{"type":"array","items":{"type":"string"},"default":[]}}},"Error":{"type":"object","properties":{"message":{"type":"string"},"code":{"type":"number"}}},"SignIn":{"required":["name","password"],"type":"object","properties":{"username":{"type":"string"},"password":{"type":"string"}}},"SignUp":{"required":["name","password","mail","secret"],"type":"object","properties":{"username":{"type":"string"},"password":{"type":"string"},"email":{"type":"string"},"secret":{"type":"string"}}},"Token":{"type":"object","properties":{"token":{"type":"string"}}}}},"paths":{"/admin/cats":{"get":{"operationId":"admin:cats:browse","security":[{"jwt":[]}],"tags":["Admin"],"description":"Browse cats","parameters":[{"name":"limit","in":"query","schema":{"type":"integer"}},{"name":"skip","in":"query","schema":{"type":"integer"}}],"responses":{"200":{"description":"List of cats","content":{"application/json":{"schema":{"type":"array","items":{"required":["file","tags","validated"],"type":"object","properties":{"_id":{"type":"string"},"validated":{"type":"boolean"},"file":{"type":"string"},"mimetype":{"type":"string"},"size":{"type":"number"},"tags":{"type":"array","items":{"type":"string"},"default":[]},"createdAt":{"type":"string","format":"date-time"},"updatedAt":{"type":"string","format":"date-time"}}}}}}}}}},"/admin/cats/{id}/validate":{"put":{"operationId":"admin:cats:validate","security":[{"jwt":[]}],"tags":["Admin"],"description":"Activate cat","parameters":[{"name":"id","in":"path","schema":{"type":"string"},"required":true}],"responses":{"200":{"description":"Cat activated"},"404":{"description":"Cat not found"}}}},"/admin/cats/{id}":{"patch":{"operationId":"admin:cats:edit","security":[{"jwt":[]}],"tags":["Admin"],"description":"Activate cat","parameters":[{"name":"id","in":"path","schema":{"type":"string"},"required":true}],"requestBody":{"content":{"application/json":{"schema":{"type":"object","properties":{"tags":{"type":"string"}}}}}},"responses":{"200":{"description":"Cat updated"},"404":{"description":"Cat not found"}}},"delete":{"operationId":"admin:cats:delete","security":[{"jwt":[]}],"tags":["Admin"],"description":"Delete cat","parameters":[{"name":"id","in":"path","schema":{"type":"string"},"required":true}],"responses":{"203":{"description":"Cat deleted"},"404":{"description":"Cat not found"}}}},"/cat":{"get":{"operationId":"cat:random","tags":["Cats"],"description":"Get a random cat","parameters":[{"name":"type","in":"query","schema":{"type":"string","enum":["square","medium","small","xsmall"]}},{"name":"filter","in":"query","schema":{"type":"string","enum":["mono","negate","custom"]}},{"name":"fit","in":"query","schema":{"type":"string","enum":["cover","contain","fill","inside","outside"]}},{"name":"position","in":"query","schema":{"type":"string","default":"center","enum":["top","right top","right","right bottom","bottom","left bottom","left","left top","center"]}},{"name":"width","in":"query","schema":{"type":"integer"}},{"name":"height","in":"query","schema":{"type":"integer"}},{"name":"blur","in":"query","schema":{"type":"integer"}},{"name":"r","in":"query","schema":{"type":"integer"},"description":"Red"},{"name":"g","in":"query","schema":{"type":"integer"},"description":"Green"},{"name":"b","in":"query","schema":{"type":"integer"},"description":"Blue"},{"name":"brightness","in":"query","schema":{"type":"number","format":"float"},"description":"Brightness multiplier"},{"name":"saturation","in":"query","schema":{"type":"number","format":"float"},"description":"Saturation multiplier"},{"name":"hue","in":"query","schema":{"type":"integer"},"description":"Hue rotation in degrees"},{"name":"lightness","in":"query","schema":{"type":"integer"},"description":"Lightness addend"},{"name":"html","in":"query","schema":{"type":"boolean"}},{"name":"json","in":"query","schema":{"type":"boolean"}}],"responses":{"200":{"description":"Cat returned","content":{"image/*":{"schema":{"type":"string","format":"binary"}},"application/json":{"schema":{"required":["file","tags"],"type":"object","properties":{"_id":{"type":"string"},"mimetype":{"type":"string"},"size":{"type":"number"},"tags":{"type":"array","items":{"type":"string"},"default":[]}}}}}}}}},"/cat/{id}":{"get":{"operationId":"cat:get","tags":["Cats"],"description":"Get cat by id","parameters":[{"name":"id","in":"path","schema":{"type":"string"},"required":true},{"name":"type","in":"query","schema":{"type":"string","enum":["square","medium","small","xsmall"]}},{"name":"filter","in":"query","schema":{"type":"string","enum":["mono","negate","custom"]}},{"name":"fit","in":"query","schema":{"type":"string","enum":["cover","contain","fill","inside","outside"]}},{"name":"position","in":"query","schema":{"type":"string","default":"center","enum":["top","right top","right","right bottom","bottom","left bottom","left","left top","center"]}},{"name":"width","in":"query","schema":{"type":"integer"}},{"name":"height","in":"query","schema":{"type":"integer"}},{"name":"blur","in":"query","schema":{"type":"integer"}},{"name":"r","in":"query","schema":{"type":"integer"},"description":"Red"},{"name":"g","in":"query","schema":{"type":"integer"},"description":"Green"},{"name":"b","in":"query","schema":{"type":"integer"},"description":"Blue"},{"name":"brightness","in":"query","schema":{"type":"number","format":"float"},"description":"Brightness multiplier"},{"name":"saturation","in":"query","schema":{"type":"number","format":"float"},"description":"Saturation multiplier"},{"name":"hue","in":"query","schema":{"type":"integer"},"description":"Hue rotation in degrees"},{"name":"lightness","in":"query","schema":{"type":"integer"},"description":"Lightness addend"},{"name":"html","in":"query","schema":{"type":"boolean"}},{"name":"json","in":"query","schema":{"type":"boolean"}}],"responses":{"200":{"description":"Cat returned","content":{"image/*":{"schema":{"type":"string","format":"binary"}},"application/json":{"schema":{"required":["file","tags"],"type":"object","properties":{"_id":{"type":"string"},"mimetype":{"type":"string"},"size":{"type":"number"},"tags":{"type":"array","items":{"type":"string"},"default":[]}}}}}},"404":{"description":"Cat not found"}}}},"/cat/{tag}":{"get":{"operationId":"cat:random:tag","tags":["Cats"],"description":"Get random cat by tag","parameters":[{"name":"tag","in":"path","schema":{"type":"string"},"required":true},{"name":"type","in":"query","schema":{"type":"string","enum":["square","medium","small","xsmall"]}},{"name":"filter","in":"query","schema":{"type":"string","enum":["mono","negate","custom"]}},{"name":"fit","in":"query","schema":{"type":"string","enum":["cover","contain","fill","inside","outside"]}},{"name":"position","in":"query","schema":{"type":"string","default":"center","enum":["top","right top","right","right bottom","bottom","left bottom","left","left top","center"]}},{"name":"width","in":"query","schema":{"type":"integer"}},{"name":"height","in":"query","schema":{"type":"integer"}},{"name":"blur","in":"query","schema":{"type":"integer"}},{"name":"r","in":"query","schema":{"type":"integer"},"description":"Red"},{"name":"g","in":"query","schema":{"type":"integer"},"description":"Green"},{"name":"b","in":"query","schema":{"type":"integer"},"description":"Blue"},{"name":"brightness","in":"query","schema":{"type":"number","format":"float"},"description":"Brightness multiplier"},{"name":"saturation","in":"query","schema":{"type":"number","format":"float"},"description":"Saturation multiplier"},{"name":"hue","in":"query","schema":{"type":"integer"},"description":"Hue rotation in degrees"},{"name":"lightness","in":"query","schema":{"type":"integer"},"description":"Lightness addend"},{"name":"html","in":"query","schema":{"type":"boolean"}},{"name":"json","in":"query","schema":{"type":"boolean"}}],"responses":{"200":{"description":"Cat returned","content":{"image/*":{"schema":{"type":"string","format":"binary"}},"application/json":{"schema":{"required":["file","tags"],"type":"object","properties":{"_id":{"type":"string"},"mimetype":{"type":"string"},"size":{"type":"number"},"tags":{"type":"array","items":{"type":"string"},"default":[]}}}}}}}}},"/cat/says/{text}":{"get":{"operationId":"cat:random:text","tags":["Cats"],"description":"Get random cat saying text","parameters":[{"name":"text","in":"path","schema":{"type":"string"},"required":true},{"name":"font","in":"query","schema":{"type":"string","default":"Impact","enum":["Andale Mono","Impact","Arial","Arial Black","Comic Sans MS","Courier New","Georgia","Times New Roman","Verdana","Webdings"]}},{"name":"fontSize","in":"query","schema":{"type":"integer","default":30}},{"name":"fontColor","in":"query","schema":{"type":"string","default":"#000"}},{"name":"fontBackground","in":"query","schema":{"type":"string","default":"none"}},{"name":"type","in":"query","schema":{"type":"string","enum":["square","medium","small","xsmall"]}},{"name":"filter","in":"query","schema":{"type":"string","enum":["mono","negate","custom"]}},{"name":"fit","in":"query","schema":{"type":"string","enum":["cover","contain","fill","inside","outside"]}},{"name":"position","in":"query","schema":{"type":"string","default":"center","enum":["top","right top","right","right bottom","bottom","left bottom","left","left top","center"]}},{"name":"width","in":"query","schema":{"type":"integer"}},{"name":"height","in":"query","schema":{"type":"integer"}},{"name":"blur","in":"query","schema":{"type":"integer"}},{"name":"r","in":"query","schema":{"type":"integer"},"description":"Red"},{"name":"g","in":"query","schema":{"type":"integer"},"description":"Green"},{"name":"b","in":"query","schema":{"type":"integer"},"description":"Blue"},{"name":"brightness","in":"query","schema":{"type":"number","format":"float"},"description":"Brightness multiplier"},{"name":"saturation","in":"query","schema":{"type":"number","format":"float"},"description":"Saturation multiplier"},{"name":"hue","in":"query","schema":{"type":"integer"},"description":"Hue rotation in degrees"},{"name":"lightness","in":"query","schema":{"type":"integer"},"description":"Lightness addend"},{"name":"html","in":"query","schema":{"type":"boolean"}},{"name":"json","in":"query","schema":{"type":"boolean"}}],"responses":{"200":{"description":"Cat returned","content":{"image/*":{"schema":{"type":"string","format":"binary"}},"application/json":{"schema":{"required":["file","tags"],"type":"object","properties":{"_id":{"type":"string"},"mimetype":{"type":"string"},"size":{"type":"number"},"tags":{"type":"array","items":{"type":"string"},"default":[]}}}}}}}}},"/cat/{id}/says/{text}":{"get":{"operationId":"cat:get:text","tags":["Cats"],"description":"Get cat by id saying text","parameters":[{"name":"id","in":"path","schema":{"type":"string"},"required":true},{"name":"text","in":"path","schema":{"type":"string"},"required":true},{"name":"font","in":"query","schema":{"type":"string","default":"Impact","enum":["Andale Mono","Impact","Arial","Arial Black","Comic Sans MS","Courier New","Georgia","Times New Roman","Verdana","Webdings"]}},{"name":"fontSize","in":"query","schema":{"type":"integer","default":30}},{"name":"fontColor","in":"query","schema":{"type":"string","default":"#000"}},{"name":"fontBackground","in":"query","schema":{"type":"string","default":"none"}},{"name":"type","in":"query","schema":{"type":"string","enum":["square","medium","small","xsmall"]}},{"name":"filter","in":"query","schema":{"type":"string","enum":["mono","negate","custom"]}},{"name":"fit","in":"query","schema":{"type":"string","enum":["cover","contain","fill","inside","outside"]}},{"name":"position","in":"query","schema":{"type":"string","default":"center","enum":["top","right top","right","right bottom","bottom","left bottom","left","left top","center"]}},{"name":"width","in":"query","schema":{"type":"integer"}},{"name":"height","in":"query","schema":{"type":"integer"}},{"name":"blur","in":"query","schema":{"type":"integer"}},{"name":"r","in":"query","schema":{"type":"integer"},"description":"Red"},{"name":"g","in":"query","schema":{"type":"integer"},"description":"Green"},{"name":"b","in":"query","schema":{"type":"integer"},"description":"Blue"},{"name":"brightness","in":"query","schema":{"type":"number","format":"float"},"description":"Brightness multiplier"},{"name":"saturation","in":"query","schema":{"type":"number","format":"float"},"description":"Saturation multiplier"},{"name":"hue","in":"query","schema":{"type":"integer"},"description":"Hue rotation in degrees"},{"name":"lightness","in":"query","schema":{"type":"integer"},"description":"Lightness addend"},{"name":"html","in":"query","schema":{"type":"boolean"}},{"name":"json","in":"query","schema":{"type":"boolean"}}],"responses":{"200":{"description":"Cat returned","content":{"image/*":{"schema":{"type":"string","format":"binary"}},"application/json":{"schema":{"required":["file","tags"],"type":"object","properties":{"_id":{"type":"string"},"mimetype":{"type":"string"},"size":{"type":"number"},"tags":{"type":"array","items":{"type":"string"},"default":[]}}}}}},"404":{"description":"Cat not found"}}}},"/cat/{tag}/says/{text}":{"get":{"operationId":"cat:random:tag:text","tags":["Cats"],"description":"Get random cat by tag saying text","parameters":[{"name":"tag","in":"path","schema":{"type":"string"},"required":true},{"name":"text","in":"path","schema":{"type":"string"},"required":true},{"name":"font","in":"query","schema":{"type":"string","default":"Impact","enum":["Andale Mono","Impact","Arial","Arial Black","Comic Sans MS","Courier New","Georgia","Times New Roman","Verdana","Webdings"]}},{"name":"fontSize","in":"query","schema":{"type":"integer","default":30}},{"name":"fontColor","in":"query","schema":{"type":"string","default":"#000"}},{"name":"fontBackground","in":"query","schema":{"type":"string","default":"none"}},{"name":"type","in":"query","schema":{"type":"string","enum":["square","medium","small","xsmall"]}},{"name":"filter","in":"query","schema":{"type":"string","enum":["mono","negate","custom"]}},{"name":"fit","in":"query","schema":{"type":"string","enum":["cover","contain","fill","inside","outside"]}},{"name":"position","in":"query","schema":{"type":"string","default":"center","enum":["top","right top","right","right bottom","bottom","left bottom","left","left top","center"]}},{"name":"width","in":"query","schema":{"type":"integer"}},{"name":"height","in":"query","schema":{"type":"integer"}},{"name":"blur","in":"query","schema":{"type":"integer"}},{"name":"r","in":"query","schema":{"type":"integer"},"description":"Red"},{"name":"g","in":"query","schema":{"type":"integer"},"description":"Green"},{"name":"b","in":"query","schema":{"type":"integer"},"description":"Blue"},{"name":"brightness","in":"query","schema":{"type":"number","format":"float"},"description":"Brightness multiplier"},{"name":"saturation","in":"query","schema":{"type":"number","format":"float"},"description":"Saturation multiplier"},{"name":"hue","in":"query","schema":{"type":"integer"},"description":"Hue rotation in degrees"},{"name":"lightness","in":"query","schema":{"type":"integer"},"description":"Lightness addend"},{"name":"html","in":"query","schema":{"type":"boolean"}},{"name":"json","in":"query","schema":{"type":"boolean"}}],"responses":{"200":{"description":"Cat returned","content":{"image/*":{"schema":{"type":"string","format":"binary"}},"application/json":{"schema":{"required":["file","tags"],"type":"object","properties":{"_id":{"type":"string"},"mimetype":{"type":"string"},"size":{"type":"number"},"tags":{"type":"array","items":{"type":"string"},"default":[]}}}}}}}}},"/api/cats":{"get":{"operationId":"api:cats","tags":["API"],"description":"Will return all cats","parameters":[{"name":"limit","in":"query","schema":{"type":"number","default":10}},{"name":"skip","in":"query","schema":{"type":"number","default":0}},{"name":"tags","in":"query","schema":{"type":"string"}}],"responses":{"200":{"description":"List of cats","content":{"application/json":{"schema":{"type":"array","items":{"required":["file","tags"],"type":"object","properties":{"_id":{"type":"string"},"mimetype":{"type":"string"},"size":{"type":"number"},"tags":{"type":"array","items":{"type":"string"},"default":[]}}}}}}}}}},"/api/tags":{"get":{"operationId":"api:tags","tags":["API"],"description":"Will return all tags","responses":{"200":{"description":"List of tags","content":{"application/json":{"schema":{"type":"array","items":{"type":"string"}}}}}}}},"/api/count":{"get":{"operationId":"api:count","tags":["API"],"description":"Count how many cat","responses":{"200":{"description":"List of tags","content":{"application/json":{"schema":{"type":"object","properties":{"count":{"type":"number"}}}}}}}}},"/security/sign-in":{"post":{"operationId":"api:security:sign-in","tags":["Security"],"requestBody":{"content":{"application/json":{"schema":{"required":["name","password"],"type":"object","properties":{"username":{"type":"string"},"password":{"type":"string"}}}}}},"responses":{"200":{"description":"Authenticated","content":{"application/json":{"schema":{"type":"object","properties":{"token":{"type":"string"}}}}}},"401":{"description":"Unauthorized"}}}},"/security/sign-up":{"post":{"operationId":"api:security:sign-up","tags":["Security"],"requestBody":{"content":{"application/json":{"schema":{"required":["name","password","mail","secret"],"type":"object","properties":{"username":{"type":"string"},"password":{"type":"string"},"email":{"type":"string"},"secret":{"type":"string"}}}}}},"responses":{"201":{"description":"Registered"},"400":{"description":"Bad request"}}}}}}'; + +export async function meme_maker({ query }: MemeMakerParams) { + const res = await openai.chat.completions.create({ + model: "gpt-4o-mini", + messages: [ + { + role: "system", + content: `Use the below openapi schema to generate a meme's image URL or a Cat image URL and return the url alone. + + MemeMaker OpenAPI Schema: + \`\`\` + ${mememaker_swagger} + \`\`\` + + Cat Image OpenAPI Schema: + \`\`\` + ${cat_swagger} + \`\`\` + + MemeMaker Useage: + - You can allow user to use external images using their public web url. + - You can allow user to use external images using their base64 encoded string. + + Basic Cat Image Useage: + - /cat Will return a random cat + - /cat/:tag Will return a random cat with a :tag, You can combine multiple tags with :tag separator, Example: https://cataas.com/cat/orange,cute + - /cat/gif Will return a random gif cat \o/ + - /cat/says/:text Will return a random cat saying :text + - /cat/:tag/says/:text Will return a random cat with a :tag and saying :text + + Notes: + - You can use cat image urls in memes. + `, + }, + { + role: "user", + content: query, + }, + ], + }); + + return { + response: res.choices[0].message.content, + }; +} diff --git a/tools/memory-manager.ts b/tools/memory-manager.ts new file mode 100644 index 0000000..0d4c3cf --- /dev/null +++ b/tools/memory-manager.ts @@ -0,0 +1,220 @@ +import { z } from "zod"; +import fs from "fs"; +import { randomUUID } from "crypto"; +import { Message } from "../interfaces/message"; +import { zodFunction } from "."; +import { ask } from "./ask"; +import { pathInDataDir } from "../config"; + +export const CreateMemorySchema = z.object({ + memory: z.string(), +}); + +export type CreateMemory = z.infer; + +export const UpdateMemorySchema = z.object({ + id: z.string(), + memory: z.string(), +}); + +export type UpdateMemory = z.infer; + +export const DeleteMemorySchema = z.object({ + id: z.string(), +}); + +export type DeleteMemory = z.infer; + +const memory_path = pathInDataDir("memories.json"); + +type Memories = Record< + string, + { + id: string; + memory: string; + created_at: string; + updated_at: string; + }[] +>; + +// if the file doesn't exist, create it +if (!fs.existsSync(memory_path)) { + fs.writeFileSync(memory_path, "{}"); +} + +function getMemories(): Memories { + return JSON.parse(fs.readFileSync(memory_path, "utf-8")); +} + +export function getMemoriesByManager(manager_id: string) { + return getMemories()[manager_id] || []; +} + +function saveMemories(memories: Memories) { + fs.writeFileSync(memory_path, JSON.stringify(memories, null, 2)); +} + +export function createMemory(params: CreateMemory, manager_id: string) { + try { + const memories = getMemories(); + memories[manager_id] = memories[manager_id] || []; + if (memories[manager_id].length >= 5) { + return { error: "You have reached the limit of memories." }; + } + const uuid = randomUUID(); + const start = Math.floor(Math.random() * (uuid.length - 4)); + const new_mem = { + id: uuid.slice(start, start + 4), + memory: params.memory, + created_at: new Date().toISOString(), + updated_at: new Date().toISOString(), + }; + memories[manager_id].push(new_mem); + saveMemories(memories); + return { id: new_mem.id }; + } catch (error) { + return { error }; + } +} + +export function updateMemory(params: UpdateMemory, manager_id: string) { + try { + const memories = getMemories(); + memories[manager_id] = memories[manager_id] || []; + const memory = memories[manager_id].find((m) => m.id === params.id); + if (!memory) { + return { error: "Memory not found" }; + } + memory.memory = params.memory; + memory.updated_at = new Date().toISOString(); + saveMemories(memories); + return {}; + } catch (error) { + return { error }; + } +} + +export function deleteMemory(params: DeleteMemory, manager_id: string) { + try { + const memories = getMemories(); + memories[manager_id] = memories[manager_id] || []; + memories[manager_id] = memories[manager_id].filter( + (m) => m.id !== params.id + ); + saveMemories(memories); + return {}; + } catch (error) { + return { error }; + } +} + +export const memory_tools = (manager_id: string) => [ + zodFunction({ + function: (args) => createMemory(args, manager_id), + name: "create_memory", + schema: CreateMemorySchema, + description: "Create a memory.", + }), + zodFunction({ + function: (args) => updateMemory(args, manager_id), + name: "update_memory", + schema: UpdateMemorySchema, + description: "Update a memory.", + }), + zodFunction({ + function: (args) => deleteMemory(args, manager_id), + name: "delete_memory", + schema: DeleteMemorySchema, + description: "Delete a memory.", + }), +]; + +const MemoryManagerSchema = z.object({ + request: z.string(), +}); + +export type MemoryManager = z.infer; + +async function memoryManager( + params: MemoryManager, + context_message: Message, + manager_id: string +) { + try { + const current_memories = getMemories()[manager_id] || []; + const tools = memory_tools(manager_id); + + const response = await ask({ + model: "gpt-4o", + prompt: `You are a Memories Manager. + +You manage memories for other managers. + +Help the manager with their request based on the information provided. + +- **Priority:** Only store useful and detailed memories. + - If the request is not useful or lacks detail, ask for more information or deny the request. +- When a manager reaches the memory limit, ask them to choose memories to delete. Ensure they inform their user about the deletion and confirm before proceeding. +- Ensure the memories are relevant to the requesting manager. +- Return the ID of any memory you save so the manager can refer to it later. + +**Current Manager:** ${manager_id} + +**Their Memories:** +${JSON.stringify(current_memories)} + `, + message: params.request, + name: manager_id, + seed: `memory-man-${manager_id}-${ + context_message.author.username ?? context_message.author.id + }`, + tools, + }); + + return { + response: response.choices[0].message.content, + }; + } catch (error) { + return { error }; + } +} + +export const memory_manager_init = ( + context_message: Message, + manager_id: string +) => { + return zodFunction({ + function: (args) => memoryManager(args, context_message, manager_id), + name: "memory_manager", + schema: MemoryManagerSchema, + description: + `Manages memories for a manager or yourself. + +- Memories are isolated per manager; managers can't access each other's memories. +- **Use Cases:** +- Remembering important user preferences. +- Anything you want to recall later. + +**Examples:** +- "Remember to use \`home_assistant_manager\` when the user asks to set text on a widget." +- "Remember that the user mainly cares about the P4 system service status." + +Memories are limited and costly; use them wisely. +` + + manager_id === + "self" + ? `### Imporant Note + Make sure you only use this for your own memories and not for other memories that you can tell other managers to remember. + ` + : "", + }); +}; + +export const memory_manager_guide = ( + manager_id: string +) => `# Memories Saved for You + +${JSON.stringify(getMemoriesByManager(manager_id), null, 2)} + +You can store up to 5 memories at a time. Use them wisely. +`; diff --git a/tools/messenger.ts b/tools/messenger.ts new file mode 100644 index 0000000..4317df8 --- /dev/null +++ b/tools/messenger.ts @@ -0,0 +1,244 @@ +// tools/tokio.ts + +import { z } from "zod"; +import { Message } from "../interfaces/message"; +import { userConfigs } from "../config"; +import fs from "fs"; +import path from "path"; +import { getMessageInterface } from "../interfaces"; + +// Utility function to get user ID by name and platform +function getUserIdByName( + userName: string, + platform: string +): string | undefined { + const userConfig = userConfigs.find( + (user) => user.name.toLowerCase() === userName.toLowerCase() + ); + if (userConfig) { + const identity = userConfig.identities.find( + (id) => id.platform === platform + ); + return identity?.id; + } + return undefined; +} + +// SendMessageParams schema +export const SendMessageParams = z.object({ + user_id: z + .string() + .describe( + "The user id of the user specific to the platform selected. This will be different from the user's name and depends on the platform." + ), + content: z + .string() + .describe( + "The message to send to the user. Make sure to include the name of the person who asked you to send the message. You can only link HTTP URLs in links; you cannot link file paths EVER." + ) + .optional(), + platform: z.string().describe("The platform to send the message to."), + embeds: z + .array( + z.object({ + title: z.string().optional(), + description: z.string().optional(), + url: z.string().optional(), + color: z.number().optional(), + timestamp: z.string().optional(), + footer: z + .object({ + text: z.string(), + icon_url: z.string().optional(), + }) + .optional(), + image: z + .object({ + url: z.string(), + }) + .optional(), + thumbnail: z + .object({ + url: z.string(), + }) + .optional(), + }) + ) + .optional() + .describe( + "Embeds to send. Include the name of the person who asked you to send the message in the footer as the from user." + ), + files: z + .array( + z.object({ + attachment: z.string().describe("URL/path to file to send"), + name: z.string(), + }) + ) + .optional(), +}); +export type SendMessageParams = z.infer; + +// Function to send a message to a user +export async function send_message_to( + { content, embeds, files, user_id, platform: plat }: SendMessageParams, + context_message: Message +) { + if (!plat) { + return { error: "Please specify a platform" }; + } + + const platform = (plat || context_message.platform).toLocaleLowerCase(); + if ( + !context_message.getUserRoles().includes("admin") && + platform === "whatsapp" + ) { + return { + error: + "You need to be Raj to send messages on WhatsApp, you are not allowed", + }; + } + + if (platform === "whatsapp") { + const roles = context_message.getUserRoles(); + if (!roles.includes("admin")) { + return { error: "User is not allowed to send messages on WhatsApp." }; + } + } + + // if platform is whatsapp and user_id does not end with @c.us, add it + if (platform === "whatsapp" && user_id && !user_id.endsWith("@c.us")) { + user_id = user_id + "@c.us"; + } + // Get the recipient's user ID + let toUserId: string | undefined = user_id; + + try { + // Prepare the message data + const messageData = { content, embeds, files }; + if (user_id) { + if (plat !== context_message.platform) { + const local_ctx = await getMessageInterface({ + platform: plat || platform, + id: user_id, + }); + try { + await local_ctx.send(messageData); + return { + response: "Message sent", + }; + } catch (error) { + return { + error, + }; + } + } + } + + if (!toUserId) { + return { error: "User not found on this platform." }; + } + + if (!content && !embeds && !files) { + return { + error: "At least one of content, embeds, or files is required.", + }; + } + + await context_message.sendDirectMessage(toUserId, messageData); + return { + response: + "Message sent, generate notification text telling that message was successfully sent.", + note: + toUserId === context_message.author.id + ? `The message was sent to the user. Reply to the user with "" as you already sent them a message.` + : "The message was sent to the user. You can also tell what you sent the user if required.", + }; + } catch (error: any) { + return { error: error.message || error }; + } +} + +// SendGeneralMessageParams schema +export const SendGeneralMessageParams = z.object({ + channel_id: z + .string() + .optional() + .describe("Channel ID to send the message to."), + content: z + .string() + .describe( + "The message to send. Make sure to include the name of the person who asked you to send the message. You can only link HTTP URLs in links; you cannot link file paths EVER." + ) + .optional(), + embeds: z + .array( + z.object({ + title: z.string().optional(), + description: z.string().optional(), + url: z.string().optional(), + color: z.number().optional(), + timestamp: z.string().optional(), + footer: z + .object({ + text: z.string(), + icon_url: z.string().optional(), + }) + .optional(), + image: z + .object({ + url: z.string(), + }) + .optional(), + thumbnail: z + .object({ + url: z.string(), + }) + .optional(), + }) + ) + .optional() + .describe( + "Embeds to send. Include the name of the person who asked you to send the message in the footer as the from user." + ), + files: z + .array( + z.object({ + attachment: z.string().describe("URL/path to file to send"), + name: z.string(), + }) + ) + .optional(), +}); +export type SendGeneralMessageParams = z.infer; + +// Function to send a message to a channel +export async function send_general_message( + { channel_id, content, embeds, files }: SendGeneralMessageParams, + context_message: Message +) { + const platform = context_message.platform; + + // Use the provided channel ID or default to the current channel + const targetChannelId = channel_id || context_message.channelId; + + if (!targetChannelId) { + return { error: "Channel ID is required." }; + } + + if (!content && !embeds && !files) { + return { error: "At least one of content, embeds, or files is required." }; + } + + try { + // Prepare the message data + const messageData = { content, embeds, files }; + + await context_message.sendMessageToChannel(targetChannelId, messageData); + return { + response: "Message sent", + }; + } catch (error: any) { + return { error: error.message || error }; + } +} diff --git a/tools/meta-fetcher.ts b/tools/meta-fetcher.ts new file mode 100644 index 0000000..eab6419 --- /dev/null +++ b/tools/meta-fetcher.ts @@ -0,0 +1,11 @@ +import metaFetcher from "meta-fetcher"; +import { z } from "zod"; + +// get meta data from url +export const MetaFetcherParams = z.object({ + url: z.string(), +}); +export type MetaFetcherParams = z.infer; +export async function meta_fetcher({ url }: MetaFetcherParams) { + return await metaFetcher(url); +} diff --git a/tools/notes.ts b/tools/notes.ts new file mode 100644 index 0000000..1d72b08 --- /dev/null +++ b/tools/notes.ts @@ -0,0 +1,496 @@ +import { createClient, ResponseDataDetailed } from "webdav"; +import { z } from "zod"; +import { zodFunction } from "."; +import { RunnableToolFunction } from "openai/lib/RunnableFunction.mjs"; +import Fuse from "fuse.js"; +import { ask } from "./ask"; +import { Message } from "../interfaces/message"; +import { memory_manager_guide, memory_manager_init } from "./memory-manager"; + +// Initialize WebDAV client +const client = createClient("http://192.168.29.85/remote.php/dav/files/raj/", { + username: process.env.NEXTCLOUD_USERNAME!, + password: process.env.NEXTCLOUD_PASSWORD!, +}); + +// Types +export type OperationResult = { success: boolean; message: string | object }; +// Schemas for function parameters +export const CreateFileParams = z.object({ + path: z.string().describe("The path for the new file."), + content: z.string().describe("The content for the new file."), +}); +export type CreateFileParams = z.infer; + +export const CreateDirectoryParams = z.object({ + path: z.string().describe("The path for the new directory."), +}); +export type CreateDirectoryParams = z.infer; + +export const DeleteItemParams = z.object({ + path: z.string().describe("The path to the file or directory to be deleted."), +}); +export type DeleteItemParams = z.infer; + +export const MoveItemParams = z.object({ + source_path: z + .string() + .describe("The current path of the file or directory."), + destination_path: z + .string() + .describe("The new path where the file or directory will be moved."), +}); +export type MoveItemParams = z.infer; + +export const SearchFilesParams = z.object({ + query: z + .string() + .describe("The query string to search for file names or content."), +}); +export type SearchFilesParams = z.infer; + +export const TagParams = z.object({ + path: z.string().describe("The path to the file to tag."), + tag: z.string().describe("The tag to add to the file."), +}); +export type TagParams = z.infer; + +// Helper function to remove the "notes/" prefix +function normalizePath(path: string): string { + return path.startsWith("notes/") ? path.substring(6) : path; +} + +// Function to create a file +export async function createFile({ + path, + content, +}: CreateFileParams): Promise { + try { + await client.putFileContents(`/notes/${normalizePath(path)}`, content); + return { success: true, message: "File created successfully" }; + } catch (error: any) { + return { success: false, message: error.message }; + } +} + +// Function to create a directory +export async function createDirectory({ + path, +}: CreateDirectoryParams): Promise { + try { + await client.createDirectory(`/notes/${normalizePath(path)}`); + return { success: true, message: "Directory created successfully" }; + } catch (error: any) { + return { success: false, message: error.message }; + } +} + +// Function to delete a file or directory +export async function deleteItem({ + path, +}: DeleteItemParams): Promise { + try { + await client.deleteFile(`/notes/${normalizePath(path)}`); + return { success: true, message: "Deleted successfully" }; + } catch (error: any) { + return { success: false, message: error.message }; + } +} + +// Function to move a file or directory +export async function moveItem({ + source_path, + destination_path, +}: MoveItemParams): Promise { + try { + await client.moveFile( + `/notes/${normalizePath(source_path)}`, + `/notes/${normalizePath(destination_path)}` + ); + return { success: true, message: "Moved successfully" }; + } catch (error: any) { + return { success: false, message: error.message }; + } +} + +// Function to search for files by name +export async function searchFilesByName({ + query, +}: SearchFilesParams): Promise { + try { + const files = await client.getDirectoryContents("notes", { + details: true, + deep: true, + }); + + // If `files` is of type `ResponseDataDetailed`, you need to access the data property + const fileList = Array.isArray(files) ? files : files.data; + + // Setup fuse.js with the filenames + const fuse = new Fuse(fileList, { + keys: ["filename"], // Search within filenames + threshold: 0.3, // Adjust this to control the fuzziness (0 = exact match, 1 = very fuzzy) + }); + + const matchingFiles = fuse.search(query).map((result) => result.item); + + return { + success: true, + message: + matchingFiles.length > 0 + ? matchingFiles.map((file) => file.filename).join(", ") + : "No matching files found", + }; + } catch (error: any) { + return { success: false, message: error.message }; + } +} + +// Function to search for files by content +export async function searchFilesByContent({ + query, +}: SearchFilesParams): Promise { + try { + const files = await client.getDirectoryContents("notes", { + details: true, + deep: true, + }); + + // If `files` is of type `ResponseDataDetailed`, you need to access the data property + const fileList = Array.isArray(files) ? files : files.data; + + // First, filter files by filename using fuse.js + const fuseFilename = new Fuse(fileList, { + keys: ["basename"], // Search within filenames + threshold: 0.3, // Adjust this to control the fuzziness + }); + const matchingFilesByName = fuseFilename + .search(query) + .map((result) => result.item); + + const matchingFilesByContent = []; + + // Then, check file content + for (const file of fileList) { + if (file.type === "file") { + const content = await client.getFileContents(file.filename, { + format: "text", + }); + const fuseContent = new Fuse([String(content)], { + threshold: 0.3, // Adjust for content search + }); + const contentMatch = fuseContent.search(query); + if (contentMatch.length > 0) { + matchingFilesByContent.push(normalizePath(file.filename)); + } + } + } + + // Combine results from filename and content search + const combinedResults = [ + ...new Set([ + ...matchingFilesByName.map((f) => f.filename), + ...matchingFilesByContent, + ]), + ]; + + return { + success: true, + message: + combinedResults.length > 0 + ? combinedResults.join(", ") + : "No matching files found", + }; + } catch (error: any) { + return { success: false, message: error.message }; + } +} + +// Placeholder for tagging functionality +export async function tagFile({ + path, + tag, +}: TagParams): Promise { + return { success: false, message: "Tagging not supported with WebDAV." }; +} + +// Placeholder for searching files by tag +export async function searchFilesByTag({ + tag, +}: TagParams): Promise { + return { success: false, message: "Tagging not supported with WebDAV." }; +} + +export async function getNotesList(): Promise { + try { + const directoryContents = await fetchDirectoryContents("notes"); + + const treeStructure = buildTree(directoryContents as any); + return { + success: true, + message: JSON.stringify(treeStructure, null, 2), + }; + } catch (error: any) { + return { + success: false, + message: error.message, + }; + } +} + +async function fetchDirectoryContents( + path: string +): Promise> { + let contents = await client.getDirectoryContents(path); + + // Normalize contents to always be an array of FileStat + if (!Array.isArray(contents)) { + contents = contents.data; // Assuming it's ResponseDataDetailed + } + + // Recursively fetch the contents of subdirectories + for (const item of contents) { + if (item.type === "directory") { + const subdirectoryContents = await fetchDirectoryContents(item.filename); + contents = contents.concat(subdirectoryContents as any); + } + } + + return contents; +} + +function buildTree(files: any[]): any { + const tree: any = {}; + + files.forEach((file) => { + const parts: string[] = file.filename.replace(/^\/notes\//, "").split("/"); + let current = tree; + + parts.forEach((part, index) => { + if (!current[part]) { + current[part] = index === parts.length - 1 ? null : {}; // Leaf nodes are set to null + } + current = current[part]; + }); + }); + + return tree; +} + +export const FetchFileContentsParams = z.object({ + path: z + .string() + .describe("The path to the file whose content is to be fetched."), +}); +export type FetchFileContentsParams = z.infer; + +// The fetchFileContents function +export async function fetchFileContents({ + path, +}: FetchFileContentsParams): Promise { + try { + // Fetch the file content from the WebDAV server + const fileContent: ResponseDataDetailed = + (await client.getFileContents(`/notes/${normalizePath(path)}`, { + format: "text", + details: true, + })) as ResponseDataDetailed; + + return { + success: true, + message: fileContent, + }; + } catch (error: any) { + return { + success: false, + message: error.message, + }; + } +} + +export const UpdateFileParams = z.object({ + path: z.string().describe("The path to the note file to be updated."), + new_content: z + .string() + .describe("The new content to replace the existing content."), +}); +export type UpdateFileParams = z.infer; + +export async function updateNote({ + path, + new_content, +}: UpdateFileParams): Promise { + try { + // Fetch the existing content to ensure the file exists and to avoid overwriting unintentionally + const existingContent = await client.getFileContents( + `/notes/${normalizePath(path)}`, + { + format: "text", + } + ); + + // Update the file with the new content + await client.putFileContents(`/notes/${normalizePath(path)}`, new_content); + + return { success: true, message: "Note updated successfully" }; + } catch (error: any) { + return { success: false, message: error.message }; + } +} + +// Integration into runnable tools +export let webdav_tools: RunnableToolFunction[] = [ + zodFunction({ + function: getNotesList, + name: "getNotesList", + schema: z.object({}), + description: "Get the list of note files and directories.", + }), + zodFunction({ + function: fetchFileContents, + name: "fetchNoteFileContents", + schema: FetchFileContentsParams, + description: "Fetch the contents of a specific note file.", + }), + zodFunction({ + function: createFile, + name: "createNoteFile", + schema: CreateFileParams, + description: "Create a new note file.", + }), + zodFunction({ + function: updateNote, + name: "updateNote", + schema: UpdateFileParams, + description: "Update an existing note.", + }), + zodFunction({ + function: createDirectory, + name: "createNoteDir", + schema: CreateDirectoryParams, + description: "Create a new directory in notes.", + }), + zodFunction({ + function: deleteItem, + name: "deleteNoteItem", + schema: DeleteItemParams, + description: "Delete a note file or directory.", + }), + zodFunction({ + function: moveItem, + name: "moveNote", + schema: MoveItemParams, + description: "Move a note file or directory.", + }), + // zodFunction({ + // function: searchFilesByName, + // name: "searchNotesFilesByName", + // schema: SearchFilesParams, + // description: "Search notes by filename.", + // }), + zodFunction({ + function: searchFilesByContent, + name: "searchNotesFilesByContent", + schema: SearchFilesParams, + description: "Search notes by content.", + }), + zodFunction({ + function: tagFile, + name: "tagNoteFile", + schema: TagParams, + description: "Add a tag to a note file.", + }), + // zodFunction({ + // function: searchFilesByTag, + // name: "searchNotesFilesByTag", + // schema: TagParams, + // description: "Search notes by tag.", + // }), +]; + +export function getNotesSystemPrompt() { + return `The notes system manages a structured file system for organizing and retrieving notes using Nextcloud via WebDAV. All notes are stored in the 'notes' directory, with subdirectories for different content types. + +**Key Directories:** + +- **Root**: Contains a 'readme' summarizing the structure. +- **Journal**: Logs daily events and activities. Subdirectories include: + - **general**: General daily events or notes. + - **standup**: Work-related standup notes. Filenames should be dates in YYYY-MM-DD format. + - **personal**: Personal life events, same format as standup notes. + - **gym**: Gym or workout activities. + +- **Lists**: Contains lists of items or tasks. Subdirectories can organize different list types. + +**Standup and Personal Note Template:** + +- **Filename**: Date in YYYY-MM-DD format. +- **Title**: Human-readable date (e.g., "Thursday 15th of July"), year not necessary. +- **Updates Section**: List of updates describing the day's events. +- **Summary Section**: A summary of the main points. + +**Gym Note Template:** + +- **Filename**: Date in YYYY-MM-DD format. +- **Title**: Gym day and date (e.g., "Pull Day - Thursday 15th of July"). +- **Activity**: Exercises performed, sets, reps, weights. +- **Progress Report**: Progress updates, achievements, challenges, comparisons with previous workouts, suggestions for improvement. + +**Lists Template:** + +- **Directory Structure**: Create subdirectories within 'lists' for different types (e.g., 'shows', 'movies', 'shopping'). +- **Filename**: Each file represents a list item with context. For 'shopping', use a single file like 'shopping.md'. + +**Functionality:** + +- Create, update, delete and move notes by filename or content. +- The \`updateNote\` function modifies existing notes. + +This system ensures efficient note management, avoiding duplication, maintaining organization, and following structured templates for work and personal notes.`; +} + +export const NotesManagerParams = z.object({ + request: z.string().describe("User's request regarding notes."), +}); +export type NotesManagerParams = z.infer; + +export async function notesManager( + { request }: NotesManagerParams, + context_message: Message +) { + const tools = webdav_tools.concat( + memory_manager_init(context_message, "notes_manager") + ); + const response = await ask({ + model: "gpt-4o", + prompt: `You are a notes manager for the 'notes' directory in Nextcloud. + +Your job is to understand the user's request (e.g., create, update, delete, move, list) and handle it using the available tools. Ensure the 'notes' directory remains organized, filenames and paths are correct, and duplication is prevented. + +Avoid running \`fetchNoteFileContents\` unnecessarily, as it fetches the entire file content and is resource-intensive. + +**More about the Notes System:** + +${getNotesSystemPrompt()} + +Follow the above guidelines to manage notes efficiently. + +---- + +${memory_manager_guide("notes_manager")} + +---- + +**Live Values:** + +- **Today's Date:** ${new Date().toDateString()} +- **Current Notes List:** +${(await getNotesList()).message} + `, + message: request, + seed: `notes-${context_message.channelId}`, + tools: tools as any, + }); + + return { response }; +} diff --git a/tools/period.ts b/tools/period.ts new file mode 100644 index 0000000..2d2b07c --- /dev/null +++ b/tools/period.ts @@ -0,0 +1,715 @@ +// tools/period.ts + +import { z, ZodSchema } from "zod"; +import { Database } from "bun:sqlite"; +import { + RunnableToolFunction, + RunnableToolFunctionWithParse, +} from "openai/lib/RunnableFunction.mjs"; +import { JSONSchema } from "openai/lib/jsonschema.mjs"; +import zodToJsonSchema from "zod-to-json-schema"; +import { ask } from "./ask"; +import cron from "node-cron"; +import { Message } from "../interfaces/message"; +import { pathInDataDir, userConfigs } from "../config"; +import { getMessageInterface } from "../interfaces"; + +// Populate example data function +export function populateExampleData() { + db.query("DELETE FROM period_cycles").run(); + db.query("DELETE FROM period_entries").run(); +} + +export function clearprdandtestdb() { + if (db) db.close(); + const prddb = usePrdDb(); + const testdb = useTestDb(); + prddb.query("DELETE FROM period_cycles").run(); + prddb.query("DELETE FROM period_entries").run(); + + testdb.query("DELETE FROM period_cycles").run(); + testdb.query("DELETE FROM period_entries").run(); +} + +// Util functions for managing menstrual cycle + +const PeriodCycleSchema = z.object({ + id: z.string(), + startDate: z.string(), + endDate: z.string(), + description: z.string(), + ended: z.boolean(), +}); + +const PeriodEntrySchema = z.object({ + id: z.string(), + date: z.string(), + description: z.string(), +}); + +export type PeriodCycleType = z.infer; +export type PeriodEntryType = z.infer; + +let db = usePrdDb(); + +function usePrdDb() { + const db_url = pathInDataDir("period.db"); + const db = new Database(db_url, { create: true }); + // Setup the tables + db.exec("PRAGMA journal_mode = WAL;"); + db.query( + `CREATE TABLE IF NOT EXISTS period_cycles ( + id TEXT PRIMARY KEY, + startDate TEXT NOT NULL, + endDate TEXT NOT NULL, + description TEXT NOT NULL, + ended BOOLEAN NOT NULL + )` + ).run(); + + db.query( + `CREATE TABLE IF NOT EXISTS period_entries ( + id TEXT PRIMARY KEY, + date TEXT NOT NULL, + description TEXT NOT NULL + )` + ).run(); + return db; +} + +function useTestDb() { + const db_url = pathInDataDir("test_period.db"); + const db = new Database(db_url, { create: true }); + // Setup the tables + db.exec("PRAGMA journal_mode = WAL;"); + db.query( + `CREATE TABLE IF NOT EXISTS period_cycles ( + id TEXT PRIMARY KEY, + startDate TEXT NOT NULL, + endDate TEXT NOT NULL, + description TEXT NOT NULL, + ended BOOLEAN NOT NULL + )` + ).run(); + + db.query( + `CREATE TABLE IF NOT EXISTS period_entries ( + id TEXT PRIMARY KEY, + date TEXT NOT NULL, + description TEXT NOT NULL + )` + ).run(); + return db; +} + +export function getPeriodCycles() { + const cycles = db.query("SELECT * FROM period_cycles").all(); + return cycles as PeriodCycleType[]; +} + +// Other utility functions remain the same... + +export function getPeriodCyclesByMonth(month_index: number, year: number) { + const startDate = new Date(year, month_index, 1).toISOString(); + const endDate = new Date(year, month_index + 1, 1).toISOString(); + const cycles = db + .query( + "SELECT * FROM period_cycles WHERE startDate >= $startDate AND startDate < $endDate" + ) + .all({ + $startDate: startDate, + $endDate: endDate, + }); + return cycles as PeriodCycleType[]; +} + +export function getPeriodCycleByDateRange(startDate: Date, endDate: Date) { + const cycles = db + .query( + "SELECT * FROM period_cycles WHERE startDate >= $startDate AND startDate < $endDate" + ) + .all({ + $startDate: startDate.toISOString(), + $endDate: endDate.toISOString(), + }); + return cycles as PeriodCycleType[]; +} + +export function createPeriodCycle( + startDate: Date, + endDate: Date, + ended?: boolean +) { + db.query( + `INSERT INTO period_cycles (id, startDate, endDate, description, ended) VALUES + ($id, $startDate, $endDate, $description, $ended)` + ).run({ + $id: Math.random().toString(36).substring(2, 15), + $startDate: startDate.toISOString(), + $endDate: endDate.toISOString(), + $description: `Started on ${startDate.toISOString()}`, + $ended: ended ? 1 : 0, + }); +} + +export function getAverageCycleLength() { + const cycles = getPeriodCycles(); + const totalLength = cycles.reduce((acc, cycle) => { + const startDate = new Date(cycle.startDate); + const endDate = new Date(cycle.endDate); + return acc + (endDate.getTime() - startDate.getTime()) / 86400000; + }, 0); + return totalLength / cycles.length; +} + +export function updateEndDatePeriodCycle(id: string, endDate: Date) { + db.query("UPDATE period_cycles SET endDate = $endDate WHERE id = $id").run({ + $id: id, + $endDate: endDate.toISOString(), + }); +} + +export function updateDiscriptionPeriodCycle(id: string, discription: string) { + db.query( + "UPDATE period_cycles SET description = $description WHERE id = $id" + ).run({ + $id: id, + $description: discription, + }); +} + +export function endPeriodCycle(id: string, discription?: string) { + db.query("UPDATE period_cycles SET ended = 1 WHERE id = $id").run({ + $id: id, + }); + updateEndDatePeriodCycle(id, new Date()); + if (discription) { + updateDiscriptionPeriodCycle(id, discription); + } +} + +export function getOngoingPeriodCycle() { + const cycle = db.query("SELECT * FROM period_cycles WHERE ended = 0").get(); + return cycle as PeriodCycleType; +} + +export function getPeriodEntries() { + const entries = db.query("SELECT * FROM period_entries").get(); + return entries as PeriodEntryType[]; +} + +export function getLatestPeriodEntry() { + const entry = db + .query("SELECT * FROM period_entries ORDER BY date DESC") + .get(); + return entry as PeriodEntryType; +} + +export function getPeriodEntriesByDateRange(startDate: Date, endDate: Date) { + const entries = db + .query( + "SELECT * FROM period_entries WHERE date >= $startDate AND date < $endDate" + ) + .all({ + $startDate: startDate.toISOString(), + $endDate: endDate.toISOString(), + }); + return entries as PeriodEntryType[]; +} + +export function getPeriodEntryByDate(date: Date) { + const entry = db + .query("SELECT * FROM period_entries WHERE date = $date") + .get({ $date: date.toISOString() }); + return entry as PeriodEntryType; +} + +export function updatePeriodEntryByDate(date: Date, description: string) { + db.query( + "UPDATE period_entries SET description = $description WHERE date = $date" + ).run({ + $date: date.toISOString(), + $description: description, + }); +} + +export function createPeriodEntry(date: Date, description: string) { + db.query( + `INSERT INTO period_entries (id, date, description) VALUES + ($id, $date, $description)` + ).run({ + $id: Math.random().toString(36).substring(2, 15), + $date: date.toISOString(), + $description: description, + }); +} + +// OpenAI tools to manage the cycles + +// Create cycle tool +export const CreatePeriodCycleParams = z.object({ + startDate: z + .string() + .describe("Date of the start of the period cycle in ISO string format IST"), + endDate: z + .string() + .describe( + "The estimated end date of the period cycle. Ask the user how long their period usually lasts and use that data to calculate this. This has to be in ISO string format IST" + ), +}); + +export type CreatePeriodCycleParamsType = z.infer< + typeof CreatePeriodCycleParams +>; + +export async function startNewPeriodCycle({ + startDate, + endDate, +}: CreatePeriodCycleParamsType) { + if (!startDate || !endDate) { + return { error: "startDate and endDate are required" }; + } + + // Check if there is an ongoing cycle + const ongoing = getOngoingPeriodCycle(); + if (ongoing) { + return { + error: "There is already an ongoing cycle", + ongoingCycle: ongoing, + }; + } + + createPeriodCycle(new Date(startDate), new Date(endDate)); + return { message: "Started a new period cycle" }; +} + +// Create old period cycle tool +export const CreateOldPeriodCycleParams = z.object({ + startDate: z + .string() + .describe("Date of the start of the period cycle in ISO string format IST"), + endDate: z + .string() + .describe( + "When did this cycle end. This has to be in ISO string format IST" + ), +}); + +export type CreateOldPeriodCycleParamsType = z.infer< + typeof CreateOldPeriodCycleParams +>; + +export async function createOldPeriodCycle({ + startDate, + endDate, +}: CreateOldPeriodCycleParamsType) { + if (!startDate || !endDate) { + return { error: "startDate and endDate are required" }; + } + + createPeriodCycle(new Date(startDate), new Date(endDate), true); + return { message: "Started a new period cycle" }; +} + +// Create entry tool +export const CreatePeriodEntryParams = z.object({ + date: z + .string() + .describe( + "Specify a date & time to add a past entry, no need to specify for a new entry" + ) + .default(new Date().toISOString()) + .optional(), + description: z + .string() + .describe("Description of the vibe the user felt on the day"), +}); + +export type CreatePeriodEntryParamsType = z.infer< + typeof CreatePeriodEntryParams +>; + +export async function addOrUpdatePeriodEntryTool({ + date, + description, +}: CreatePeriodEntryParamsType) { + date = date || (new Date().toISOString() as string); + + try { + const cycles = getPeriodCycleByDateRange( + new Date(new Date().setFullYear(new Date().getFullYear() - 1)), + new Date() + ); + if (cycles.length === 0) { + return { + error: + "You cannot update or add to a cycle that's more than a year old", + }; + } + + const cycle = cycles.find( + (cycle) => + new Date(date as string) >= new Date(cycle.startDate) && + new Date(date as string) <= new Date(cycle.endDate) + ); + + if (!cycle) { + console.log( + cycle, + "error: The specified date does not seem to be part of any existing cycle. Please check the date and/or start a new cycle from this date and try again." + ); + return { + error: + "The specified date does not seem to be part of any existing cycle. Please check the date and/or start a new cycle from this date and try again.", + }; + } + + createPeriodEntry(new Date(date), description); + return { + message: "Added a new entry", + }; + } catch (error) { + console.log(error); + return { + error: "An error occurred while processing the request", + }; + } +} + +// End cycle tool + +export const EndPeriodCycleParams = z.object({ + description: z + .string() + .describe("How did the user feel during this cycle on average"), +}); + +export type EndPeriodCycleParamsType = z.infer; + +export async function endPeriodCycleTool({ + description, +}: EndPeriodCycleParamsType) { + const ongoingCycle = getOngoingPeriodCycle(); + const id = ongoingCycle ? ongoingCycle.id : null; + + if (!id) { + return { error: "There is no ongoing cycle" }; + } + + endPeriodCycle(id, description); + return { message: "Ended the period cycle" }; +} + +// Get current cycle tool +export const GetCurrentPeriodCycleParams = z.object({}); + +export type GetCurrentPeriodCycleParamsType = z.infer< + typeof GetCurrentPeriodCycleParams +>; + +export async function getCurrentPeriodCycleTool() { + try { + const cycle = getOngoingPeriodCycle(); + + console.log(cycle); + + // Days since period started + const noOfDaysSinceStart = Math.floor( + (new Date().getTime() - new Date(cycle.startDate).getTime()) / 86400000 + ); + + const averageCycleLength = getAverageCycleLength(); + + let note = + averageCycleLength > 4 + ? noOfDaysSinceStart > averageCycleLength + ? "Cycle is overdue" + : "" + : undefined; + + if (cycle.ended) { + note = + "There are no ongoing cycles. This is just the last cycle that ended."; + } + + if (!cycle.ended) { + const endDate = new Date(cycle.endDate); + if (endDate < new Date()) { + note = "Cycle is overdue, or you forgot to end the cycle."; + } + } + + const response = { + cycle, + todaysDate: new Date().toISOString(), + noOfDaysSinceStart: cycle.ended ? undefined : noOfDaysSinceStart, + averageCycleLength, + note, + }; + + return response; + } catch (error) { + console.log(error); + return { + error: "No ongoing cycle", + }; + } +} + +// Get entries in a date range tool +export const GetPeriodEntriesParams = z.object({ + startDate: z.string().describe("Start date in ISO string format IST"), + endDate: z.string().describe("End date in ISO string format IST"), +}); + +export type GetPeriodEntriesParamsType = z.infer; + +export async function getPeriodEntriesTool({ + startDate, + endDate, +}: GetPeriodEntriesParamsType) { + const entries = getPeriodEntriesByDateRange( + new Date(startDate), + new Date(endDate) + ); + return entries; +} + +// Get vibe by date range tool +export const GetVibeByDateRangeParams = z.object({ + startDate: z.string().describe("Start date in ISO string format IST"), + endDate: z.string().describe("End date in ISO string format IST"), +}); + +export type GetVibeByDateRangeParamsType = z.infer< + typeof GetVibeByDateRangeParams +>; + +export async function getVibeByDateRangeTool({ + startDate, + endDate, +}: GetVibeByDateRangeParamsType) { + const entries = getPeriodEntriesByDateRange( + new Date(startDate), + new Date(endDate) + ); + + ask({ + prompt: `Give me the general summary from the below entries that are a part of a period cycle: + ---- + [${entries.map((entry) => entry.description).join("\n")}] + ---- + + The above are entries from ${startDate} to ${endDate} + You need to give a general short summary of how the user felt during this period. + `, + }); + + return entries; +} + +// Get cycle by date range tool +export const GetPeriodCycleByDateRangeParams = z.object({ + startDate: z.string().describe("Start date in ISO string format IST"), + endDate: z.string().describe("End date in ISO string format IST"), +}); + +export type GetPeriodCycleByDateRangeParamsType = z.infer< + typeof GetPeriodCycleByDateRangeParams +>; + +export async function getPeriodCycleByDateRangeTool({ + startDate, + endDate, +}: GetPeriodCycleByDateRangeParamsType) { + const cycles = getPeriodCycleByDateRange( + new Date(startDate), + new Date(endDate) + ); + return cycles; +} + +// Get latest period entry tool +export const GetLatestPeriodEntryParams = z.object({}); +export type GetLatestPeriodEntryParamsType = z.infer< + typeof GetLatestPeriodEntryParams +>; + +export async function getLatestPeriodEntryTool() { + const entry = getLatestPeriodEntry(); + return entry; +} + +// Updated getPeriodTools function +export function getPeriodTools( + context_message: Message +): RunnableToolFunction[] { + const userRoles = context_message.getUserRoles(); + + if (!userRoles.includes("periodUser")) { + // User does not have access to period tools + return []; + } + + db.close(); + db = usePrdDb(); + + return [ + zodFunction({ + function: startNewPeriodCycle, + name: "startNewPeriodCycle", + schema: CreatePeriodCycleParams, + description: `Start a new period cycle. + You can specify the start date and end date. + You need to ask how the user is feeling and make a period entry about this.`, + }), + zodFunction({ + function: createOldPeriodCycle, + name: "createOldPeriodCycle", + schema: CreateOldPeriodCycleParams, + description: `Create a period cycle that has already ended. + If the user wants to add entries of older period cycles, you can create a cycle that has already ended. + Ask the user for the start date and end date of the cycle in natural language. + `, + }), + zodFunction({ + function: addOrUpdatePeriodEntryTool, + name: "addOrUpdatePeriodEntry", + schema: CreatePeriodEntryParams, + description: `Add or update a period entry. If the entry for the date already exists, it will be updated.`, + }), + zodFunction({ + function: endPeriodCycleTool, + name: "endPeriodCycle", + schema: EndPeriodCycleParams, + description: `End ongoing period cycle. Make sure to confirm with the user before ending the cycle. + Ask the user if their cycle needs to be ended if it's been more than 7 days since the start date of the cycle.`, + }), + zodFunction({ + function: getCurrentPeriodCycleTool, + name: "getCurrentPeriodCycle", + schema: GetCurrentPeriodCycleParams, + description: `Get the ongoing period cycle. + This returns the ongoing period cycle, the number of days since the cycle started, and the average cycle length. + `, + }), + zodFunction({ + function: getPeriodEntriesTool, + name: "getPeriodEntriesByDateRange", + schema: GetPeriodEntriesParams, + description: "Get period entries in a date range", + }), + zodFunction({ + function: getPeriodCycleByDateRangeTool, + name: "getPeriodCycleByDateRange", + schema: GetPeriodCycleByDateRangeParams, + description: "Get period cycles in a date range", + }), + zodFunction({ + function: getLatestPeriodEntryTool, + name: "getLatestPeriodEntry", + schema: GetLatestPeriodEntryParams, + description: "Get the latest period entry", + }), + zodFunction({ + function: getVibeByDateRangeTool, + name: "getVibeByDateRange", + schema: GetVibeByDateRangeParams, + description: `Get the general vibe of the user in a date range. + This will ask the user to give a general summary of how they felt during this period. + `, + }), + ]; +} + +export function zodFunction({ + function: fn, + schema, + description = "", + name, +}: { + function: (args: T) => Promise; + schema: ZodSchema; + description?: string; + name?: string; +}): RunnableToolFunctionWithParse { + return { + type: "function", + function: { + function: fn, + name: name ?? fn.name, + description: description, + parameters: zodToJsonSchema(schema) as JSONSchema, + parse(input: string): T { + const obj = JSON.parse(input); + return schema.parse(obj); + }, + }, + }; +} + +// Updated startPeriodJob function +var jobStarted = false; +export function startPeriodJob() { + if (jobStarted) return; + const timezone = "Asia/Kolkata"; + cron.schedule( + "0 */4 * * *", + async () => { + console.log("Checking for period entries in the last 2 hours"); + + // Get users with 'periodUser' role but not 'testingPeriodUser' + const periodUsers = userConfigs.filter( + (user) => + user.roles.includes("periodUser") && + !user.roles.includes("testingPeriodUser") + ); + + for (const user of periodUsers) { + // Assuming you have a function to send messages to users based on their identities + for (const identity of user.identities) { + // Fetch or create a Message object for each user identity + const context_message: Message = await getMessageInterface(identity); + + const cycle = getOngoingPeriodCycle(); + if (!cycle) continue; + + const entry = getLatestPeriodEntry(); + const isOldEntry = + new Date(entry.date) < new Date(new Date().getTime() - 14400000); + + if (isOldEntry) { + const message_for_user = await ask({ + prompt: `Generate a message to remind the user to make a period entry. + + Ask the user how they are feeling about their period cycle as it's been a while since they updated how they felt. + Do not explicitly ask them to make an entry, just ask them how they are feeling about their period. + + Today's date: ${new Date().toISOString()} + + Ongoing cycle: ${JSON.stringify(cycle)} + + Note: if the end date is in the past then ask the user if the cycle is still going on or if it's okay to end the cycle. + + Last entry: ${JSON.stringify(entry)}`, + }); + + if (message_for_user.choices[0].message.content) { + await context_message.send({ + content: message_for_user.choices[0].message.content, + }); + } else { + console.log("No message generated"); + } + } + } + } + }, + { + timezone, + recoverMissedExecutions: true, + runOnInit: true, + } + ); + jobStarted = true; +} diff --git a/tools/python-interpreter.ts b/tools/python-interpreter.ts new file mode 100644 index 0000000..30b8682 --- /dev/null +++ b/tools/python-interpreter.ts @@ -0,0 +1,194 @@ +// tools/python-interpreter.ts + +import { nanoid } from "nanoid"; +import fs from "fs"; +import os from "os"; +import path from "path"; +import { exec } from "child_process"; +import { z } from "zod"; +import { Message } from "../interfaces/message"; +import QuickChart from "quickchart-js"; +import { $ } from "zx"; + +// Utility function to run Python code in an existing Docker container +async function runPythonCodeInExistingDocker( + pythonCode: string, + dependencies: string[] = [], + uid: string +) { + const containerName = `python-runner-${uid}`; + + // Check if container exists; if not, create it + const op = + await $`docker ps -a --filter "name=${containerName}" --format "{{.Names}}"`; + if (op.stdout.trim() === containerName) { + console.log("Container exists"); + } else { + console.log("Container does not exist, creating it"); + await $`docker run -d --name ${containerName} -v /tmp:/tmp python:3.10 tail -f /dev/null`; + } + + return await new Promise((resolve, reject) => { + const tempFileName = `tempScript-${nanoid()}.py`; + const tempFilePath = path.join(os.tmpdir(), tempFileName); + + fs.writeFile(tempFilePath, pythonCode, (err) => { + if (err) { + console.error(`Error writing Python script to file: ${err}`); + reject(`Error writing Python script to file: ${err}`); + return; + } + + const dockerCommand = `docker exec ${containerName} python /tmp/${tempFileName}`; + + console.log("Executing Docker command:", dockerCommand); + + exec(dockerCommand, (error, stdout, stderr) => { + setTimeout(() => { + fs.unlink(tempFilePath, (unlinkErr) => { + if (unlinkErr) { + console.error(`Error deleting temporary file: ${unlinkErr}`); + } + }); + }, 60000); + + if (error) { + console.error(`Error executing Python script: ${error}`); + reject(`${error}\nTry to fix the above error`); + return; + } + if (stderr) { + console.error(`stderr: ${stderr}`); + } + console.log("Python script executed successfully.", stdout); + resolve(stdout); + }); + }); + }); +} + +// Python code interpreter +export const PythonCodeParams = z.object({ + code: z.string().describe("The Python 3.10 code to run"), +}); +export type PythonCodeParams = z.infer; + +export async function code_interpreter( + { code }: PythonCodeParams, + context_message: Message +) { + try { + const output = await runPythonCodeInExistingDocker( + code, + [], + context_message.id + ); + return { output }; + } catch (error) { + return { error }; + } +} + +// Run bash command in the above Docker container +export const RunPythonCommandParams = z.object({ + command: z.string().describe("The command to run"), +}); +export type RunPythonCommandParams = z.infer; + +export async function run_command_in_code_interpreter_env( + { command }: RunPythonCommandParams, + context_message: Message +): Promise { + const containerName = `python-runner-${context_message.id}`; + + // Check if container exists; if not, create it + const op = + await $`docker ps -a --filter "name=${containerName}" --format "{{.Names}}"`; + if (op.stdout.trim() === containerName) { + console.log("Container exists"); + } else { + console.log("Container does not exist, creating it"); + await $`docker run -d --name ${containerName} -v /tmp:/tmp python:3.10 tail -f /dev/null`; + } + + const dockerCommand = `docker exec ${containerName} ${command}`; + + console.log("Executing Docker command:", dockerCommand); + + return await new Promise((resolve, reject) => { + exec(dockerCommand, (error, stdout, stderr) => { + if (error) { + console.error(`Error executing command: ${error}`); + reject({ + error: `Error executing command: ${error}`, + }); + return; + } + if (stderr) { + console.error(`stderr: ${stderr}`); + } + console.log("Command executed successfully."); + resolve({ output: stdout }); + }); + }); +} + +// Generate chart image URL using quickchart.io +export const ChartParams = z.object({ + chart_config: z.object({ + type: z.string().optional(), + data: z.object({ + labels: z.array(z.string()).optional(), + datasets: z.array( + z.object({ + label: z.string().optional(), + data: z.array(z.number()).optional(), + backgroundColor: z.string().optional(), + borderColor: z.string().optional(), + borderWidth: z.number().optional(), + }) + ), + }), + options: z.object({ + title: z.object({ + display: z.boolean().optional(), + text: z.string().optional(), + }), + }), + }), +}); +export type ChartParams = z.infer; + +export async function chart({ chart_config }: ChartParams) { + try { + const myChart = new QuickChart(); + myChart.setConfig(chart_config); + const chart_url = await myChart.getShortUrl(); + return { chart_url }; + } catch (error) { + return { error }; + } +} + +// Send file to user +export const SendFileParams = z.object({ + file_url: z + .string() + .describe( + "File URL. This can be a web URL or a direct file path from code interpreter '/tmp/file.png'. Try checking if the file exists before sending it." + ), + file_name: z.string().describe("File name, use .png for images"), +}); +export type SendFileParams = z.infer; + +export async function send_file( + { file_url, file_name }: SendFileParams, + context_message: Message +) { + try { + await context_message.sendFile(file_url, file_name); + return { response: "File sent" }; + } catch (error) { + return { error }; + } +} diff --git a/tools/reminders.ts b/tools/reminders.ts new file mode 100644 index 0000000..5f8f3f2 --- /dev/null +++ b/tools/reminders.ts @@ -0,0 +1,585 @@ +import axios, { AxiosError } from "axios"; +import { z } from "zod"; +import { zodFunction } from "."; +import { RunnableToolFunction } from "openai/lib/RunnableFunction.mjs"; +import { ask } from "./ask"; +import { Message } from "../interfaces/message"; +import { memory_manager_guide, memory_manager_init } from "./memory-manager"; + +const NEXTCLOUD_API_ENDPOINT = + "http://192.168.29.85/remote.php/dav/calendars/raj/"; +const NEXTCLOUD_USERNAME = process.env.NEXTCLOUD_USERNAME; +const NEXTCLOUD_PASSWORD = process.env.NEXTCLOUD_PASSWORD; + +if (!NEXTCLOUD_USERNAME || !NEXTCLOUD_PASSWORD) { + throw new Error( + "Please provide NEXTCLOUD_USERNAME and NEXTCLOUD_PASSWORD environment variables." + ); +} + +const TASKS_CALENDAR_NAME = "anya"; + +const apiClient = axios.create({ + baseURL: NEXTCLOUD_API_ENDPOINT, + auth: { + username: NEXTCLOUD_USERNAME, + password: NEXTCLOUD_PASSWORD, + }, + headers: { + "Content-Type": "application/xml", // Ensure correct content type for DAV requests + }, +}); + +// Schemas for each function's parameters +export const TaskParams = z.object({ + task_id: z.string().describe("The unique ID of the task."), +}); +export type TaskParams = z.infer; + +export const CreateTaskParams = z.object({ + summary: z.string().describe("The summary (title) of the task."), + description: z.string().optional().describe("The description of the task."), + due_date: z + .string() + .optional() + .describe("The due date of the task in ISO 8601 format."), + priority: z.number().optional().describe("The priority of the task (1-9)."), + all_day: z + .boolean() + .optional() + .describe("Whether the task is an all-day event."), + recurrence: z + .string() + .optional() + .describe("The recurrence rule for the task in RRULE format."), +}); +export type CreateTaskParams = z.infer; + +// Functions +export async function createTask({ + summary, + description, + due_date, + priority, + all_day, + recurrence, +}: CreateTaskParams): Promise { + const uid = Date.now(); // Use a timestamp as a UID for simplicity + + const formatDueDate = ( + date: string | undefined, + allDay: boolean | undefined + ) => { + if (!date) return ""; + const d = new Date(date); + if (allDay) { + return `${d.getUTCFullYear()}${(d.getUTCMonth() + 1) + .toString() + .padStart(2, "0")}${d.getUTCDate().toString().padStart(2, "0")}`; + } else { + return formatDateTime(date); + } + }; + + const icsContent = [ + "BEGIN:VCALENDAR", + "VERSION:2.0", + "PRODID:-//Your Company//Your Product//EN", + "BEGIN:VTODO", + `UID:${uid}@cloud.raj.how`, + `SUMMARY:${summary}`, + `DESCRIPTION:${description || ""}`, + due_date + ? `${all_day ? "DUE;VALUE=DATE" : "DUE"}:${formatDueDate( + due_date, + all_day + )}\r\n` + : "", + priority ? `PRIORITY:${priority}` : "", + recurrence ? `RRULE:${recurrence}` : "", + `DTSTAMP:${formatDateTime(new Date().toISOString())}`, + all_day && due_date + ? `DTSTART;VALUE=DATE:${formatDueDate(due_date, all_day)}` + : "", + !all_day && due_date ? `DTSTART:${formatDateTime(due_date)}` : "", + "STATUS:NEEDS-ACTION", + "END:VTODO", + "END:VCALENDAR", + ] + .filter(Boolean) + .join("\r\n"); // Ensure no empty lines and correct formatting + + try { + const response = await apiClient.put( + `${TASKS_CALENDAR_NAME}/${uid}.ics`, + icsContent, + { + headers: { + "Content-Type": "text/calendar", + }, + } + ); + return { response: "Task created successfully" }; + } catch (error) { + console.log( + "Failed to create task:", + (error as AxiosError).response?.data || (error as AxiosError).message + ); + return { + error: `Error: ${ + (error as AxiosError).response?.data || (error as AxiosError).message + }`, + }; + } +} + +export const UpdateTaskParams = z.object({ + task_id: z.string().describe("The unique ID of the task to update."), + summary: z.string().optional().describe("The updated summary of the task."), + description: z + .string() + .optional() + .describe("The updated description of the task."), + due_date: z + .string() + .optional() + .describe("The updated due date of the task in ISO 8601 format."), + priority: z + .number() + .optional() + .describe("The updated priority of the task (1-9)."), + all_day: z + .boolean() + .optional() + .describe("Whether the task is an all-day event."), + recurrence: z + .string() + .optional() + .describe("The updated recurrence rule for the task in RRULE format."), +}); +export type UpdateTaskParams = z.infer; + +export async function updateTask({ + task_id, + summary, + description, + due_date, + priority, + all_day, + recurrence, +}: UpdateTaskParams): Promise { + const existingTaskUrl = `${NEXTCLOUD_API_ENDPOINT}${TASKS_CALENDAR_NAME}/${task_id}.ics`; + + const retryAttempts = 3; + const retryDelay = 1000; // 1 second delay between retries + + const formatDueDate = ( + date: string | undefined, + allDay: boolean | undefined + ) => { + if (!date) return ""; + const d = new Date(date); + if (allDay) { + return `${d.getUTCFullYear()}${(d.getUTCMonth() + 1) + .toString() + .padStart(2, "0")}${d.getUTCDate().toString().padStart(2, "0")}`; + } else { + return formatDateTime(date); + } + }; + + for (let attempt = 1; attempt <= retryAttempts; attempt++) { + try { + console.log( + `Fetching existing task from: ${existingTaskUrl} (Attempt ${attempt})` + ); + const existingTaskResponse = await apiClient.get(existingTaskUrl, { + responseType: "text", + }); + + let existingTaskData = existingTaskResponse.data; + + // Modify the fields in the existing task data + if (summary) { + existingTaskData = existingTaskData.replace( + /SUMMARY:.*\r\n/, + `SUMMARY:${summary}\r\n` + ); + } + if (description) { + existingTaskData = existingTaskData.replace( + /DESCRIPTION:.*\r\n/, + `DESCRIPTION:${description}\r\n` + ); + } + if (due_date) { + const formattedDueDate = formatDueDate(due_date, all_day); + const dueRegex = /DUE(;VALUE=DATE)?:.*\r\n/; + + // Replace existing DUE field if it exists, otherwise add it + if (dueRegex.test(existingTaskData)) { + existingTaskData = existingTaskData.replace( + dueRegex, + `${all_day ? "DUE;VALUE=DATE" : "DUE"}:${formattedDueDate}\r\n` + ); + } else { + existingTaskData = existingTaskData.replace( + "STATUS:NEEDS-ACTION", + `${ + all_day ? "DUE;VALUE=DATE" : "DUE" + }:${formattedDueDate}\r\nSTATUS:NEEDS-ACTION` + ); + } + } + if (priority) { + existingTaskData = existingTaskData.replace( + /PRIORITY:.*\r\n/, + `PRIORITY:${priority}\r\n` + ); + } + if (recurrence) { + if (existingTaskData.includes("RRULE")) { + existingTaskData = existingTaskData.replace( + /RRULE:.*\r\n/, + `RRULE:${recurrence}\r\n` + ); + } else { + existingTaskData = existingTaskData.replace( + "STATUS:NEEDS-ACTION", + `RRULE:${recurrence}\r\nSTATUS:NEEDS-ACTION` + ); + } + } + + if (all_day !== undefined) { + const dtstartRegex = /DTSTART(;VALUE=DATE)?:(\d{8}(T\d{6}Z)?)\r\n/; + if (all_day) { + // If all_day is true, ensure DTSTART is in DATE format + if (dtstartRegex.test(existingTaskData)) { + existingTaskData = existingTaskData.replace( + dtstartRegex, + `DTSTART;VALUE=DATE:${formatDueDate(due_date, all_day)}\r\n` + ); + } else { + existingTaskData = existingTaskData.replace( + "STATUS:NEEDS-ACTION", + `DTSTART;VALUE=DATE:${formatDueDate( + due_date, + all_day + )}\r\nSTATUS:NEEDS-ACTION` + ); + } + } else { + // If all_day is false, ensure DTSTART is in DATE-TIME format + if (dtstartRegex.test(existingTaskData)) { + existingTaskData = existingTaskData.replace( + dtstartRegex, + `DTSTART:${formatDateTime( + due_date || new Date().toISOString() + )}\r\n` + ); + } else { + existingTaskData = existingTaskData.replace( + "STATUS:NEEDS-ACTION", + `DTSTART:${formatDateTime( + due_date || new Date().toISOString() + )}\r\nSTATUS:NEEDS-ACTION` + ); + } + } + } + + console.log("Updating task with new data..."); + const response = await apiClient.put(existingTaskUrl, existingTaskData, { + headers: { + "Content-Type": "text/calendar", + }, + }); + + console.log("Task updated successfully:", response.status); + return { response: "Task updated successfully" }; + } catch (error) { + const axiosError = error as AxiosError; + + // Check for 404 error indicating the task was not found + if (axiosError.response?.status === 404) { + console.log(`Task not found on attempt ${attempt}. Retrying...`); + if (attempt < retryAttempts) { + await new Promise((res) => setTimeout(res, retryDelay)); // Wait before retrying + continue; // Retry the operation + } else { + return { + error: `Error: Task not found with ID: ${task_id} after ${retryAttempts} attempts. Please check if the task exists.`, + }; + } + } + + // Log other errors + console.log( + `Failed to update task on attempt ${attempt}:`, + axiosError.response?.data || axiosError.message + ); + return { + error: `Error: ${axiosError.response?.data || axiosError.message}`, + }; + } + } + + // Fallback return in case nothing else is returned (should not be reached) + return { error: "An unexpected error occurred." }; +} + +export async function deleteTask({ task_id }: TaskParams) { + try { + const deleteUrl = `${NEXTCLOUD_API_ENDPOINT}${TASKS_CALENDAR_NAME}/${task_id}.ics`; + console.log(`Attempting to delete task at: ${deleteUrl}`); + + const response = await apiClient.delete(deleteUrl); + console.log("Task deleted successfully:", response.status); + return { response: "Task deleted successfully" }; + } catch (error) { + console.log( + "Failed to delete task:", + (error as AxiosError).response?.data || (error as AxiosError).message + ); + return { + error: `Error: ${ + (error as AxiosError).response?.data || (error as AxiosError).message + }`, + }; + } +} + +export async function listTasks({ + start_time, + end_time, +}: { + start_time: string; + end_time: string; +}): Promise { + try { + const startISOTime = convertToISOFormat(start_time); + const endISOTime = convertToISOFormat(end_time); + + const allTasks: any[] = []; + const calendarUrl = `${NEXTCLOUD_API_ENDPOINT}${TASKS_CALENDAR_NAME}/`; + console.log(`Accessing tasks calendar URL: ${calendarUrl}`); + + try { + const testResponse = await apiClient.get(calendarUrl); + console.log(`Test response for ${calendarUrl}: ${testResponse.status}`); + } catch (testError) { + console.error( + `Error accessing ${calendarUrl}: ${(testError as AxiosError).message}` + ); + return []; + } + + console.log( + `Making REPORT request to ${calendarUrl} for tasks between ${startISOTime} and ${endISOTime}` + ); + + let reportResponse; + try { + reportResponse = await apiClient.request({ + method: "REPORT", + url: calendarUrl, + headers: { Depth: "1" }, + data: ` + + + + + + + + + +`, + }); + console.log(`REPORT request successful: Status ${reportResponse.status}`); + } catch (reportError) { + console.error( + `REPORT request failed for ${calendarUrl}: ${ + (reportError as AxiosError).response?.data || + (reportError as AxiosError).message + }` + ); + return []; + } + + console.log(`Parsing iCal response for tasks`); + const icsFiles = parseICalResponse(reportResponse.data); + + for (const icsFile of icsFiles) { + const fullIcsUrl = `http://192.168.29.85${icsFile}?export`; + const taskId = icsFile.split("/").pop()?.replace(".ics", ""); + console.log(`Fetching task data from ${fullIcsUrl}`); + + try { + const taskResponse = await apiClient.get(fullIcsUrl, { + responseType: "text", + }); + const taskData = taskResponse.data; + + // Identify all-day events + const isAllDay = taskData.includes("DTSTART;VALUE=DATE"); + + const parsedTask = { + task_id: taskId, + summary: taskData.match(/SUMMARY:(.*)\r\n/)?.[1], + description: taskData.match(/DESCRIPTION:(.*)\r\n/)?.[1], + due_date: isAllDay + ? taskData.match(/DUE;VALUE=DATE:(\d{8})\r\n/)?.[1] + : taskData.match(/DUE:(\d{8}T\d{6}Z)/)?.[1], + all_day: isAllDay, + recurrence: taskData.match(/RRULE:(.*)\r\n/)?.[1], + }; + + allTasks.push(parsedTask); + console.log( + `Task data fetched and parsed successfully from ${fullIcsUrl}` + ); + } catch (taskError) { + console.error( + `Failed to fetch task data from ${fullIcsUrl}: ${ + (taskError as AxiosError).response?.data || + (taskError as AxiosError).message + }` + ); + } + } + + return allTasks; + } catch (error) { + console.log( + "Final catch block error:", + (error as AxiosError).response?.data || (error as AxiosError).message + ); + return { + error: `Error: ${ + (error as AxiosError).response?.data || (error as AxiosError).message + }`, + }; + } +} + +// Helper function to convert datetime to ISO format in UTC +function formatDateTime(dateTime: string): string { + const date = new Date(dateTime); + const year = date.getUTCFullYear().toString().padStart(4, "0"); + const month = (date.getUTCMonth() + 1).toString().padStart(2, "0"); + const day = date.getUTCDate().toString().padStart(2, "0"); + const hours = date.getUTCHours().toString().padStart(2, "0"); + const minutes = date.getUTCMinutes().toString().padStart(2, "0"); + const seconds = date.getUTCSeconds().toString().padStart(2, "0"); + return `${year}${month}${day}T${hours}${minutes}${seconds}Z`; // UTC format required by iCalendar +} + +// Integration into runnable tools +export let reminders_tools: RunnableToolFunction[] = [ + zodFunction({ + function: createTask, + name: "createReminder", + schema: CreateTaskParams, + description: `Create a new task (reminder). + +Before creating a task, run \`listReminders\` to check if it already exists and can be updated instead. + +If a similar task exists, ask the user if they want to update it instead of creating a new one.`, + }), + zodFunction({ + function: updateTask, + name: "updateReminder", + schema: UpdateTaskParams, + description: "Update an existing task (reminder).", + }), + zodFunction({ + function: deleteTask, + name: "deleteReminder", + schema: TaskParams, + description: "Delete a task (reminder).", + }), + zodFunction({ + function: listTasks, + name: "listReminders", + schema: z.object({ + start_time: z.string().describe("Start time in ISO 8601 format."), + end_time: z.string().describe("End time in ISO 8601 format."), + }), + description: "List tasks (reminders) within a specified time range.", + }), +]; + +export function getReminderSystemPrompt() { + return `Manage your tasks and reminders using these functions to create, update, delete, and list reminders. + +Keep track of important tasks and deadlines programmatically. + +Use correct ISO 8601 time formats and handle task IDs carefully. + +Fetch task data before updating or deleting to avoid errors or duplication. + +Determine a priority level based on the user's tone and urgency of the task.`; +} + +// Helper function to convert datetime to ISO format in UTC +function convertToISOFormat(dateTime: string): string { + const date = new Date(dateTime); + return date.toISOString().replace(/[-:]/g, "").split(".")[0] + "Z"; +} + +// Helper function to parse iCal response +function parseICalResponse(response: string): string[] { + const hrefRegex = /([^<]+)<\/d:href>/g; + const matches = []; + let match; + while ((match = hrefRegex.exec(response)) !== null) { + matches.push(match[1]); + } + return matches; +} + +export const RemindersManagerParams = z.object({ + request: z.string().describe("User's request regarding reminders or tasks."), +}); +export type RemindersManagerParams = z.infer; + +export async function remindersManager( + { request }: RemindersManagerParams, + context_message: Message +) { + const currentTime = new Date(); + const endOfMonth = new Date( + currentTime.getFullYear(), + currentTime.getMonth() + 1, + 0 + ); + + const response = await ask({ + model: "gpt-4o-mini", + prompt: `You are a reminders and tasks manager for the 'anya' calendar system. + +Your job is to understand the user's request (e.g., create, update, delete, list reminders) and handle it using the available tools. Use the correct ISO 8601 time format for reminders and provide feedback about the specific action taken. + +---- +${memory_manager_guide("reminders_manager")} +---- + +Current Time: ${currentTime.toISOString()} + +This Month's Reminders (${currentTime.toLocaleString()} to ${endOfMonth.toLocaleString()}): +${await listTasks({ + start_time: currentTime.toISOString(), + end_time: endOfMonth.toISOString(), +})} + `, + tools: reminders_tools.concat( + memory_manager_init(context_message, "reminders_manager") + ) as any, + message: request, + seed: `reminders-${context_message.channelId}`, + }); + + return { response }; +} diff --git a/tools/resend.ts b/tools/resend.ts new file mode 100644 index 0000000..9f34e39 --- /dev/null +++ b/tools/resend.ts @@ -0,0 +1,237 @@ +import { z } from "zod"; +import { Resend } from "resend"; +import { ask } from "./ask"; + +const resend_key = process.env.RESEND_API_KEY?.trim(); + +if (!resend_key) { + throw new Error("RESEND_API_KEY is required"); +} + +const resend = new Resend(resend_key); + +export const ResendParams = z.object({ + to: z.string().email(), + subject: z.string(), + html: z.string(), +}); + +export type ResendParams = z.infer; + +export async function send_email({ to, subject, html }: ResendParams) { + if (to.includes("example.com")) { + return { + error: + "Invalid email, this is just an example email please find the user's real email using search user id tool", + }; + } + + try { + await resend.emails.send({ + from: "anya@tri.raj.how", + to, + subject, + html: + (await formatToHtml({ + to, + subject, + html, + })) ?? html, + }); + return { + response: "Email sent", + }; + } catch (error) { + return { + error, + }; + } +} + +const vercel_invite_template = ` + + + + + + + + + + +
Join Alan on Vercel
 ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏
+
+ + + + + + + + +
+ + + + + + +
Vercel
+

Join Enigma on Vercel

+

Hello alanturing,

+

Alan (alan.turing@example.com) has invited you to the Enigma team on Vercel.

+ + + + + + +
+ + + + + + + + +
invited you to
+
+ + + + + + +
Join the team
+

or copy and paste this URL into your browser: https://vercel.com/teams/invite/foo

+
+

This invitation was intended for alanturing. This invite was sent from 204.13.186.218 located in São Paulo, Brazil. If you were not expecting this invitation, you can ignore this email. If you are concerned about your account's safety, please reply to this email to get in touch with us.

+
+ + +`; + +const stripe_welcome_template = ` + + + + + + + +
You're now ready to make live transactions with Stripe!
 ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏
+
+ + + + + + + + +
+ + + + + + +
Stripe +
+

Thanks for submitting your account information. You're now ready to make live transactions with Stripe!

+

You can view your payments and a variety of other information about your account right from your dashboard.

View your Stripe Dashboard +
+

If you haven't finished your integration, you might find our docs handy.

+

Once you're ready to start accepting payments, you'll just need to use your live API keys instead of your test API keys. Your account can simultaneously be used for both test and live requests, so you can continue testing while accepting live payments. Check out our tutorial about account basics.

+

Finally, we've put together a quick checklist to ensure your website conforms to card network standards.

+

We'll be here to help you with any step along the way. You can find answers to most questions and get in touch with us on our support site.

+

— The Stripe team

+
+

Stripe, 354 Oyster Point Blvd, South San Francisco, CA 94080

+
+
+ + +`; + +const linear_login_code_template = ` + + + + + + + +
Your login code for Linear
 ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏ ‌​‍‎‏
+
+ + + + + + + + +
Linear +

Your login code for Linear

+ + + + + + +
Login to Linear
+

This link and code will only be valid for the next 5 minutes. If the link does not work, you can use the login verification code directly:

tt226-5398x +
Linear +
+ + +`; + +// use ask function to take some data and pick a relavent template and put the data in it and return the final html string +async function formatToHtml({ + to, + subject, + html, +}: { + to: string; + subject: string; + html: string; +}) { + const response = await ask({ + model: "gpt-4o-mini", + prompt: `Given some subject and html content + + To: ${to} + Subject: ${subject} + HTML: ${html} + + Example Templates to Pick from: + 1. Vercel Invite Template: + ${vercel_invite_template} + + 2. Stripe Welcome Template: + ${stripe_welcome_template} + + 3. Linear Login Code Template: + ${linear_login_code_template} + + Pick a template and put the data in it to create the final HTML string. + Do not Make up false data, use only the given data. + + RETURN ONLY HTML STRING + `, + }); + return response.choices[0].message.content + ? extractHtmlString(response.choices[0].message.content) + : null; +} + +function extractHtmlString(response: string): string { + // Use a regular expression to match the HTML string within the response + const htmlMatch = response.match(/]*>([\s\S]*?)<\/html>/i); + + // Return the matched HTML content or an empty string if no match is found + return htmlMatch ? htmlMatch[0] : ""; +} diff --git a/tools/schedule.ts b/tools/schedule.ts new file mode 100644 index 0000000..ae1ffa4 --- /dev/null +++ b/tools/schedule.ts @@ -0,0 +1,25 @@ +import { Message } from "discord.js"; +import { z } from "zod"; + +// get time function +const GetTimeParams = z.object({}); +type GetTimeParams = z.infer; +async function get_time({}: GetTimeParams) { + return { time: new Date().toLocaleTimeString() }; +} + +// schedule a message to be sent in the future +export const ScheduleMessageParams = z.object({ + message: z.string(), + delay: z.number().describe("delay in milliseconds"), +}); +export type ScheduleMessageParams = z.infer; +export async function schedule_message( + { message, delay }: ScheduleMessageParams, + context_message: Message +) { + setTimeout(() => { + context_message.channel.send(message); + }, delay); + return { response: "scheduled message" }; +} diff --git a/tools/scrape.ts b/tools/scrape.ts new file mode 100644 index 0000000..0fd5ff3 --- /dev/null +++ b/tools/scrape.ts @@ -0,0 +1,109 @@ +import puppeteer from "puppeteer"; +import TurndownService from "turndown"; +import { z } from "zod"; +import { ask } from "./ask"; + +interface ScrapedData { + meta: { + title: string; + description: string; + coverImage: string; + [key: string]: string; + }; + body: string; +} + +async function scrapeAndConvertToMarkdown(url: string): Promise { + try { + // Launch Puppeteer browser + const browser = await puppeteer.launch(); + const page = await browser.newPage(); + + // Navigate to the URL + await page.goto(url, { waitUntil: "networkidle2" }); + + // Extract metadata and body content using Puppeteer + const result = await page.evaluate(() => { + const meta: any = { + title: document.querySelector("head > title")?.textContent || "", + description: + document + .querySelector('meta[name="description"]') + ?.getAttribute("content") || "", + coverImage: + document + .querySelector('meta[property="og:image"]') + ?.getAttribute("content") || "", + }; + + const body = document.querySelector("body")?.innerHTML || ""; + + return { meta, body }; + }); + + // Close Puppeteer browser + await browser.close(); + + // Initialize Turndown service + const turndownService = new TurndownService(); + + // Convert HTML to Markdown + const markdown = turndownService.turndown(result.body); + + // Structure the return object + const scrapedData: ScrapedData = { + meta: result.meta, + body: markdown, + }; + + return scrapedData; + } catch (error) { + console.error("Error fetching or converting content:", error); + throw new Error("Failed to scrape and convert content"); + } +} + +// Define the parameters schema using Zod +export const ScrapeAndConvertToMarkdownParams = z.object({ + url: z.string().describe("The URL of the webpage to scrape"), + summary: z + .boolean() + .default(true) + .optional() + .describe("Whether to return a summary or the entire content"), + summary_instructions: z.string().optional() + .describe(`Instructions for summarizing the content. + Example: "Return only the author list and their affiliations not the full website content." + This can be used to: + 1. Filter out information that is not needed. + 2. Scope the summary to a specific part of the content. + 3. Provide context for the summary. + 4. Extracting specific information from the content / formatting. +`), +}); + +export type ScrapeAndConvertToMarkdownParams = z.infer< + typeof ScrapeAndConvertToMarkdownParams +>; + +export async function scrape_and_convert_to_markdown({ + url, + summary, +}: ScrapeAndConvertToMarkdownParams) { + try { + const result = await scrapeAndConvertToMarkdown(url); + if (summary) { + const summaryResult = await ask({ + prompt: `Summarize the following content: \n\n${result.body}`, + model: "groq-small", + }); + return { + meta: result.meta, + summary: summaryResult.choices[0].message.content, + }; + } + return result; + } catch (error) { + return { error }; + } +} diff --git a/tools/search-user.ts b/tools/search-user.ts new file mode 100644 index 0000000..d588d40 --- /dev/null +++ b/tools/search-user.ts @@ -0,0 +1,41 @@ +import { z } from "zod"; +import { userConfigs } from "../config"; +import { ask } from "./ask"; +import { Message } from "../interfaces/message"; + +export const SearchUserParams = z.object({ + name: z.string().describe("The name of the user to search for."), + platform: z + .string() + .optional() + .describe( + "The platform to search for the user, this will default to discord." + ), +}); + +export type SearchUserParams = z.infer; + +export async function search_user( + { name, platform }: SearchUserParams, + context_message: Message +) { + try { + const res = await ask({ + prompt: `You are a Search Tool that takes in a name and platform and returns the user's details. You are searching for ${name} on ${platform}. + + You need to search for the user in the user config 1st. + ${JSON.stringify(userConfigs)} + + Return found user in a simple format. + `, + }); + console.log(res.choices[0].message); + return { + response: res.choices[0].message, + }; + } catch (error) { + return { + error, + }; + } +} diff --git a/tools/status.ts b/tools/status.ts new file mode 100644 index 0000000..732ffb7 --- /dev/null +++ b/tools/status.ts @@ -0,0 +1,59 @@ +import OpenAI from "openai"; +import { z } from "zod"; + +// get meta data from url +export const ServiceCheckerParams = z.object({ + query: z.string(), +}); + +export type ServiceCheckerParams = z.infer; + +const ai_token = process.env.OPENAI_API_KEY?.trim(); +const openai = new OpenAI({ + apiKey: ai_token, +}); + +export async function service_checker({ query }: ServiceCheckerParams) { + const status_pages = [ + "http://192.168.29.85:3001/status/tokio", + "https://ark-status.raj.how/status/ark", + ]; + + // fetch the html of the status pages + const status_page_html_promises = await Promise.allSettled( + status_pages.map(async (url) => { + const res = await fetch(url); + return res.text(); + }) + ); + + const status_page_html = status_page_html_promises.map((res) => { + if (res.status === "fulfilled") { + return res.value; + } + return res.reason; + }); + + const res = await openai.chat.completions.create({ + model: "gpt-4o-mini", + messages: [ + { + role: "system", + content: `You are a service status bot that takes in a user query about a service and responds with the status of the service. + + The HTML of the status pages is: "${status_page_html}". + + The user query is: "${query}". + `, + }, + { + role: "user", + content: query, + }, + ], + }); + + return { + response: res.choices[0].message.content, + }; +} diff --git a/tools/whatsapp.ts b/tools/whatsapp.ts new file mode 100644 index 0000000..ee5bd3a --- /dev/null +++ b/tools/whatsapp.ts @@ -0,0 +1,26 @@ +// tool to search whatsapp contacts + +import { z } from "zod"; +import { whatsappAdapter } from "../interfaces"; + +export const SearchContactsParams = z.object({ + query: z.string().min(3).max(50), +}); + +export type SearchContactsParams = z.infer; + +// Function to search contacts +export async function search_whatsapp_contacts({ + query, +}: SearchContactsParams) { + try { + const res = await whatsappAdapter.searchUser(query); + return { + results: res, + }; + } catch (error) { + return { + error, + }; + } +} diff --git a/tools/youtube.ts b/tools/youtube.ts new file mode 100644 index 0000000..6b6aa69 --- /dev/null +++ b/tools/youtube.ts @@ -0,0 +1,231 @@ +import OpenAI from "openai"; +import { TranscriptResponse, YoutubeTranscript } from "youtube-transcript"; +import { z } from "zod"; +import ytdl from "ytdl-core"; +import crypto from "crypto"; +import fs from "fs"; +import { encoding_for_model } from "@dqbd/tiktoken"; +import { ask } from "./ask"; +import { pathInDataDir } from "../config"; + +export const YoutubeTranscriptParams = z.object({ + url: z.string(), + mode: z + .enum(["summary", "full"]) + .default("summary") + .describe( + "summary or full transcript if user needs something specific out of the video, use full only when the user explicitly asks for it." + ), + query: z + .string() + .optional() + .describe( + "anything specific to look for in the video, use this for general search queries like 'when was x said in this video' or 'what was the best part of this video'" + ), +}); +export type YoutubeTranscriptParams = z.infer; + +export async function get_youtube_video_data({ + url, + query, + mode, +}: YoutubeTranscriptParams) { + let youtube_meta_data: + | { + title: string; + description: string | null; + duration: string; + author: string; + views: string; + publishDate: string; + thumbnailUrl: string; + } + | string; + let transcripts: TranscriptResponse[] | string = ""; + + try { + youtube_meta_data = await getYouTubeVideoMetadata(url); + } catch (error) { + console.error(error); + youtube_meta_data = JSON.stringify(error); + } + + try { + transcripts = await YoutubeTranscript.fetchTranscript(url); + } catch (error) { + console.error(error); + transcripts = JSON.stringify(error); + } + + const summary = + mode === "summary" + ? await summerize_video( + `youtube_meta_data: + ${ + typeof youtube_meta_data === "string" + ? "error fetching meta data, but transcripts maybe available." + : JSON.stringify({ + title: youtube_meta_data.title, + description: youtube_meta_data.description, + duration: youtube_meta_data.duration, + author: youtube_meta_data.author, + publishing_date: youtube_meta_data.publishDate, + }) + } + + transcripts: + ${ + typeof transcripts === "string" + ? "error fetching transcripts" + : JSON.stringify(transcripts) + } + `, + query + ) + : undefined; + + return { + youtube_meta_data, + summary, + transcripts: mode === "full" ? transcripts : undefined, + }; +} + +const ai_token = process.env.OPENAI_API_KEY?.trim(); + +// save summaries by updating a summary.json file with a hash for the input text +function save_summary(text: string, summary: string) { + const hash = crypto.createHash("sha256"); + hash.update(text); + const hash_text = hash.digest("hex"); + + const summariesPath = pathInDataDir("summary.json"); + let summaries: Record = {}; + try { + summaries = require(summariesPath); + } catch (error) { + console.error("Error loading summaries", error); + } + summaries[hash_text] = summary; + fs.writeFileSync(summariesPath, JSON.stringify(summaries)); +} + +function get_summary(text: string) { + const hash = crypto.createHash("sha256"); + hash.update(text); + const hash_text = hash.digest("hex"); + + const summariesPath = pathInDataDir("summary.json"); + let summaries = null; + try { + summaries = fs.readFileSync(summariesPath); + } catch (error) { + fs.writeFileSync(summariesPath, JSON.stringify({})); + } + + if (!summaries) { + return null; + } + + try { + return JSON.parse(summaries.toString())[hash_text]; + } catch (error) { + console.error("Failed to parse summaries", error); + return null; + } +} + +function numTokensFromString(message: string) { + const encoder = encoding_for_model("gpt-3.5-turbo"); + + const tokens = encoder.encode(message); + encoder.free(); + return tokens.length; +} + +async function summerize_video(text: string, query?: string) { + const openai = new OpenAI({ + apiKey: ai_token, + }); + + const saved_summary = get_summary(text); + + if (saved_summary && query) { + text = saved_summary; + } else if (saved_summary) { + return saved_summary; + } + + const res = await ask({ + model: "groq-small", + prompt: `Summarize all of the youtube info about the given youtube video. + + Youtube Data: + ----- + ${text} + ----- + Use the time stamps if available to point out the most important parts of the video or to highlight what the user was looking for in the video. + Make sure to link these timed sections so the user can click on the link and directly go to that part of the video. + Highlights should include things like something about the topic of the title or the description and not something about the author's self-promotion or the channel itself. + `, + }); + + res.choices[0].message.content && + save_summary(text, res.choices[0].message.content); + + return res.choices[0].message.content; +} + +async function getYouTubeVideoMetadata(url: string) { + try { + const info = await ytdl.getInfo(url); + const videoDetails = info.videoDetails; + + const metadata = { + title: videoDetails.title, + description: videoDetails.description, + duration: videoDetails.lengthSeconds, // in seconds + author: videoDetails.author.name, + views: videoDetails.viewCount, + publishDate: videoDetails.publishDate, + thumbnailUrl: + videoDetails.thumbnails[videoDetails.thumbnails.length - 1]?.url, + }; + + return metadata; + } catch (error) { + console.error("Error fetching video metadata:", error); + return "Error fetching video metadata"; + } +} + +// youtube downloader tool +export const YoutubeDownloaderParams = z.object({ + url: z.string(), + + quality: z.enum([ + "highest", + "lowest", + "highestaudio", + "lowestaudio", + "highestvideo", + "lowestvideo", + ]), +}); + +export type YoutubeDownloaderParams = z.infer; + +export async function get_download_link({ + url, + quality, +}: YoutubeDownloaderParams) { + try { + const info = await ytdl.getInfo(url); + const link = ytdl.chooseFormat(info.formats, { quality: quality }); + + return link.url; + } catch (error) { + console.error("Error fetching video metadata:", error); + return "Error fetching video metadata"; + } +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..7556e1d --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "lib": ["ESNext"], + "module": "esnext", + "target": "esnext", + "moduleResolution": "bundler", + "moduleDetection": "force", + "allowImportingTsExtensions": true, + "noEmit": true, + "composite": true, + "strict": true, + "downlevelIteration": true, + "skipLibCheck": true, + "jsx": "react-jsx", + "allowSyntheticDefaultImports": true, + "forceConsistentCasingInFileNames": true, + "allowJs": true, + "types": [ + "bun-types" // add Bun global + ] + } +} diff --git a/usage.ts b/usage.ts new file mode 100644 index 0000000..a9c81bf --- /dev/null +++ b/usage.ts @@ -0,0 +1,153 @@ +import * as fs from "fs"; +import * as path from "path"; +import { pathInDataDir } from "./config"; + +// Define interfaces +interface ApiUsage { + date: string; + model: string; + promptTokens: number; + completionTokens: number; + totalTokens: number; +} + +interface UsageMetrics { + totalPromptTokens: number; + totalCompletionTokens: number; + totalTokens: number; + model: string; +} + +// Define the directory for storage +const STORAGE_DIR = pathInDataDir("apiUsageData"); + +// Ensure the storage directory exists +if (!fs.existsSync(STORAGE_DIR)) { + fs.mkdirSync(STORAGE_DIR); +} + +// Function to get the file path for a specific date +function getFilePath(date: string): string { + return path.join(STORAGE_DIR, `${date}.json`); +} + +// Function to read data from a file +function readDataFromFile(filePath: string): ApiUsage[] { + if (!fs.existsSync(filePath)) { + return []; + } + const rawData = fs.readFileSync(filePath, "utf-8"); + return JSON.parse(rawData) as ApiUsage[]; +} + +// Function to write data to a file +function writeDataToFile(filePath: string, data: ApiUsage[]): void { + const jsonData = JSON.stringify(data, null, 2); + fs.writeFileSync(filePath, jsonData, "utf-8"); +} + +// Function to save API usage data +function saveApiUsage( + date: string, + model: string, + promptTokens: number, + completionTokens: number +): void { + const filePath = getFilePath(date); + let apiUsageData = readDataFromFile(filePath); + let existingData = apiUsageData.find((usage) => usage.model === model); + + if (existingData) { + existingData.promptTokens += promptTokens; + existingData.completionTokens += completionTokens; + existingData.totalTokens += promptTokens + completionTokens; + } else { + apiUsageData.push({ + date, + model, + promptTokens, + completionTokens, + totalTokens: promptTokens + completionTokens, + }); + } + + writeDataToFile(filePath, apiUsageData); +} + +// Function to calculate usage metrics based on a date range +function getTotalUsage(fromDate: string, toDate: string): UsageMetrics[] { + const from = new Date(fromDate); + const to = new Date(toDate); + let usageMetrics: { [model: string]: UsageMetrics } = {}; + + for (let d = from; d <= to; d.setDate(d.getDate() + 1)) { + const filePath = getFilePath(d.toISOString().split("T")[0]); + const dailyUsage = readDataFromFile(filePath); + + dailyUsage.forEach((usage) => { + if (!usageMetrics[usage.model]) { + usageMetrics[usage.model] = { + model: usage.model, + totalPromptTokens: 0, + totalCompletionTokens: 0, + totalTokens: 0, + }; + } + + usageMetrics[usage.model].totalPromptTokens += usage.promptTokens; + usageMetrics[usage.model].totalCompletionTokens += usage.completionTokens; + usageMetrics[usage.model].totalTokens += usage.totalTokens; + }); + } + + return Object.values(usageMetrics); +} + +// Function to get total completion tokens for a specific model +function getTotalCompletionTokensForModel( + model: string, + fromDate: string, + toDate: string +): { promptTokens: number; completionTokens: number } { + const from = new Date(fromDate); + const to = new Date(toDate); + let promptTokens = 0; + let completionTokens = 0; + + for (let d = from; d <= to; d.setDate(d.getDate() + 1)) { + const filePath = getFilePath(d.toISOString().split("T")[0]); + const dailyUsage = readDataFromFile(filePath); + + dailyUsage.forEach((usage) => { + if (usage.model === model) { + promptTokens += usage.promptTokens; + completionTokens += usage.completionTokens; + } + }); + } + + return { promptTokens, completionTokens }; +} + +// Function to delete usage data older than a specified date +function deleteOldUsageData(beforeDate: string): void { + const before = new Date(beforeDate); + + fs.readdirSync(STORAGE_DIR).forEach((file) => { + const filePath = path.join(STORAGE_DIR, file); + const fileDate = file.split(".json")[0]; + if (new Date(fileDate) < before) { + fs.unlinkSync(filePath); + } + }); +} + +// Export the module +export { + saveApiUsage, + getTotalUsage, + getTotalCompletionTokensForModel, + deleteOldUsageData, + ApiUsage, + UsageMetrics, +};