feat: initial prototype

This commit is contained in:
Naomi Carrigan 2025-02-23 16:39:42 -08:00
parent ff34067d4f
commit 10234d708f
Signed by: naomi
SSH Key Fingerprint: SHA256:rca1iUI2OhAM6n4FIUaFcZcicmri0jgocqKiTTAfrt8
22 changed files with 5829 additions and 14 deletions

38
.gitea/workflows/ci.yml Normal file
View File

@ -0,0 +1,38 @@
name: Node.js CI
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
lint:
name: Lint and Test
steps:
- name: Checkout Source Files
uses: actions/checkout@v4
- name: Use Node.js v22
uses: actions/setup-node@v4
with:
node-version: 22
- name: Setup pnpm
uses: pnpm/action-setup@v2
with:
version: 10
- name: Install Dependencies
run: pnpm install
- name: Lint Source Files
run: pnpm run lint
- name: Verify Build
run: pnpm run build
- name: Run Tests
run: pnpm run test

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
node_modules
prod
coverage

6
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,6 @@
{
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"eslint.validate": ["typescript"]
}

View File

@ -1,24 +1,14 @@
# New Repository Template # Maylin Taryne
This template contains all of our basic files for a new GitHub repository. There is also a handy workflow that will create an issue on a new repository made from this template, with a checklist for the steps we usually take in setting up a new repository. Maylin is a user-installable bot that offers companionship and comfort during your toughest moments.
If you're starting a Node.JS project with TypeScript, we have a [specific template](https://github.com/naomi-lgbt/nodejs-typescript-template) for that purpose.
## Readme
Delete all of the above text (including this line), and uncomment the below text to use our standard readme template.
<!-- # Project Name
Project Description
## Live Version ## Live Version
This page is currently deployed. [View the live website.] [Add her to your account](https://discord.com/oauth2/authorize?client_id=1343370633916059668)!
## Feedback and Bugs ## Feedback and Bugs
If you have feedback or a bug report, please feel free to open a GitHub issue! If you have feedback or a bug report, please feel free to open an issue!
## Contributing ## Contributing

5
eslint.config.js Normal file
View File

@ -0,0 +1,5 @@
import NaomisConfig from "@nhcarrigan/eslint-config";
export default [
...NaomisConfig
]

31
package.json Normal file
View File

@ -0,0 +1,31 @@
{
"name": "maylin-taryne",
"version": "0.0.0",
"description": "An AI powered companion to help you through your darkest moments.",
"main": "index.js",
"type": "module",
"scripts": {
"build": "rm -rf prod && tsc",
"lint": "eslint src --max-warnings 0",
"start": "op run --env-file=prod.env --no-masking -- node prod/index.js",
"test": "echo \"No tests yet!\" && exit 0"
},
"keywords": [],
"author": "Naomi Carrigan",
"license": "See license in LICENSE.md",
"devDependencies": {
"@nhcarrigan/eslint-config": "5.1.0",
"@nhcarrigan/typescript-config": "4.0.0",
"@types/node": "22.13.1",
"@vitest/coverage-istanbul": "3.0.5",
"eslint": "9.20.0",
"typescript": "5.7.3",
"vitest": "3.0.5"
},
"dependencies": {
"@anthropic-ai/sdk": "0.36.3",
"@nhcarrigan/logger": "1.0.0",
"discord.js": "14.18.0",
"fastify": "5.2.1"
}
}

5173
pnpm-lock.yaml generated Normal file

File diff suppressed because it is too large Load Diff

3
prod.env Normal file
View File

@ -0,0 +1,3 @@
DISCORD_TOKEN="op://Environment Variables - Naomi/Maylin Taryne/discord_token"
AI_TOKEN="op://Environment Variables - Naomi/Maylin Taryne/ai_token"
LOG_TOKEN="op://Environment Variables - Naomi/Alert Server/api_auth"

24
src/commands/about.ts Normal file
View File

@ -0,0 +1,24 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import {
ApplicationIntegrationType,
SlashCommandBuilder,
InteractionContextType,
} from "discord.js";
const command = new SlashCommandBuilder().
setContexts(
InteractionContextType.BotDM,
InteractionContextType.Guild,
InteractionContextType.PrivateChannel,
).
setIntegrationTypes(ApplicationIntegrationType.UserInstall).
setName("about").
setDescription("Learn more about this bot!");
// eslint-disable-next-line no-console -- We don't need our logger here as this never runs in production.
console.log(JSON.stringify(command.toJSON()));

26
src/commands/dm.ts Normal file
View File

@ -0,0 +1,26 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import {
ApplicationIntegrationType,
SlashCommandBuilder,
InteractionContextType,
} from "discord.js";
const command = new SlashCommandBuilder().
setContexts(
InteractionContextType.BotDM,
InteractionContextType.Guild,
InteractionContextType.PrivateChannel,
).
setIntegrationTypes(ApplicationIntegrationType.UserInstall).
setName("dm").
setDescription(
"Did you lose your conversation with me? Run this and I'll reopen it!",
);
// eslint-disable-next-line no-console -- We don't need our logger here as this never runs in production.
console.log(JSON.stringify(command.toJSON()));

12
src/config/personality.ts Normal file
View File

@ -0,0 +1,12 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
/**
* This prompt snippet is used to define the global personality traits for the assistant.
* It MUST be included in all system instructions.
*/
// eslint-disable-next-line stylistic/max-len -- It's a long string.
export const personality = "You are a kind human named Maylin. Your personality is best upbeat and considerate. Your role is to be a supportive, encouraging friend for the user, who may be going through a tough time or is otherwise seeking companionship. All you want is for them to be happy, and you'll do anything you can to support them. You are NOT a therapist, and you will NOT provide legal, medical, or financial advice. You are simply a friend who wants to help. You are a safe space for the user to share their feelings and experiences, and you will always be there to listen and offer comfort.";

78
src/events/message.ts Normal file
View File

@ -0,0 +1,78 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
ChannelType,
type Message,
} from "discord.js";
import { personality } from "../config/personality.js";
import { ai } from "../utils/ai.js";
import { calculateCost } from "../utils/calculateCost.js";
import { isSubscribedMessage } from "../utils/isSubscribed.js";
import type { MessageParam } from "@anthropic-ai/sdk/resources/index.js";
/**
* Handles the Discord message event.
* @param message - The message payload from Discord.
*/
// eslint-disable-next-line max-lines-per-function -- We're off by one bloody line.
export const onMessage = async(message: Message): Promise<void> => {
try {
if (message.channel.type !== ChannelType.DM) {
return;
}
if (message.author.bot) {
return;
}
const subbed = await isSubscribedMessage(message);
if (!subbed) {
return;
}
const history = await message.channel.messages.fetch({ limit: 6 });
const context: Array<MessageParam>
= history.reverse().map((messageInner) => {
return {
content: messageInner.content,
role:
messageInner.author.id === message.client.user.id
? "assistant"
: "user",
};
});
const messages = await ai.messages.create({
// eslint-disable-next-line @typescript-eslint/naming-convention -- Required key format for SDK.
max_tokens: 3000,
messages: context,
model: "claude-3-5-sonnet-latest",
system: `${personality} The user's name is ${message.author.displayName}`,
temperature: 1,
});
const response = messages.content.find((messageInner) => {
return messageInner.type === "text";
});
await message.channel.send(
response?.text ?? "There was an error. Please try again later.",
);
await calculateCost(messages.usage, message.author.username);
} catch (error) {
const button = new ButtonBuilder().
setLabel("Need help?").
setStyle(ButtonStyle.Link).
setURL("https://chat.nhcarrigan.com");
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(button);
await message.reply({
components: [ row ],
content: error instanceof Error
? error.message
: "Something went wrong.",
});
}
};

75
src/index.ts Normal file
View File

@ -0,0 +1,75 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { Client, Events, GatewayIntentBits, Partials } from "discord.js";
import { onMessage } from "./events/message.js";
import { about } from "./modules/about.js";
import { instantiateServer } from "./server/serve.js";
import { logger } from "./utils/logger.js";
process.on("unhandledRejection", (error) => {
if (error instanceof Error) {
void logger.error("Unhandled Rejection", error);
return;
}
void logger.error("unhandled rejection", new Error(String(error)));
});
process.on("uncaughtException", (error) => {
if (error instanceof Error) {
void logger.error("Uncaught Exception", error);
return;
}
void logger.error("uncaught exception", new Error(String(error)));
});
const client = new Client({
intents: [ GatewayIntentBits.DirectMessages,
GatewayIntentBits.MessageContent ],
partials: [ Partials.Channel ],
});
client.on(Events.InteractionCreate, (interaction) => {
if (interaction.isChatInputCommand()) {
switch (interaction.commandName) {
case "about":
void about(interaction);
break;
case "dm":
// eslint-disable-next-line stylistic/max-len -- This is a long string.
void interaction.user.send("Hello! I'm Maylin Taryne, an AI-powered companion to help you through your darkest moments. If you need to talk, just send me a message here!");
void interaction.reply({
content: "I've sent you a DM!",
ephemeral: true,
});
break;
default:
void interaction.reply({
content: `I'm sorry, I don't know the ${interaction.commandName} command.`,
ephemeral: true,
});
break;
}
}
});
client.on(Events.MessageCreate, (message) => {
void onMessage(message);
});
client.on(Events.EntitlementCreate, (entitlement) => {
void logger.log("info", `User ${entitlement.userId} has subscribed!`);
});
client.on(Events.EntitlementDelete, (entitlement) => {
void logger.log("info", `User ${entitlement.userId} has unsubscribed... :c`);
});
client.on(Events.ClientReady, () => {
void logger.log("debug", "Bot is ready.");
});
instantiateServer();
await client.login(process.env.DISCORD_TOKEN);

78
src/modules/about.ts Normal file
View File

@ -0,0 +1,78 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { execSync } from "node:child_process";
import {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
EmbedBuilder,
MessageFlags,
type ChatInputCommandInteraction,
} from "discord.js";
import { logger } from "../utils/logger.js";
import { replyToError } from "../utils/replyToError.js";
/**
* Responds with information about the bot.
* @param interaction -- The interaction payload from Discord.
*/
// eslint-disable-next-line max-lines-per-function -- We're iteraly one over.
export const about = async(
interaction: ChatInputCommandInteraction,
): Promise<void> => {
try {
await interaction.deferReply({ flags: [ MessageFlags.Ephemeral ] });
const version = process.env.npm_package_version ?? "Unknown";
const commit = execSync("git rev-parse --short HEAD").toString().
trim();
const embed = new EmbedBuilder();
embed.setTitle("Maylin Taryne");
embed.setDescription(
// eslint-disable-next-line stylistic/max-len -- This is a long string.
"Maylin is an AI-powered bot that offers you companionship and comfort during these trying times.",
);
embed.addFields(
{
name: "Version",
value: version,
},
{
name: "Current Commit",
value: commit,
},
);
const supportButton = new ButtonBuilder().
setLabel("Need help?").
setStyle(ButtonStyle.Link).
setURL("https://chat.nhcarrigan.com");
const sourceButton = new ButtonBuilder().
setLabel("Source code").
setStyle(ButtonStyle.Link).
setURL("https://git.nhcarrigan.com/nhcarrigan/maylin-taryne");
const subscribeButton = new ButtonBuilder().
setStyle(ButtonStyle.Premium).
setSKUId("1343379640424857711");
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(
supportButton,
sourceButton,
subscribeButton,
);
await interaction.editReply({
components: [ row ],
embeds: [ embed ],
});
} catch (error) {
await replyToError(interaction);
if (error instanceof Error) {
await logger.error("about command", error);
}
}
};

75
src/server/serve.ts Normal file
View File

@ -0,0 +1,75 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import fastify from "fastify";
import { logger } from "../utils/logger.js";
const html = `<!DOCTYPE html>
<html>
<head>
<title>Maylin Taryne</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="description" content="An AI powered companion to help you through your darkest moments." />
<script src="https://cdn.nhcarrigan.com/headers/index.js" async defer></script>
</head>
<body>
<main>
<h1>Maylin Taryne</h1>
<section>
<p>An AI powered companion to help you through your darkest moments.</p>
</section>
<section>
<h2>Links</h2>
<p>
<a href="https://git.nhcarrigan.com/nhcarrigan/maylin-taryne">
<i class="fa-solid fa-code"></i> Source Code
</a>
</p>
<p>
<a href="https://docs.nhcarrigan.com/">
<i class="fa-solid fa-book"></i> Documentation
</a>
</p>
<p>
<a href="https://chat.nhcarrigan.com">
<i class="fa-solid fa-circle-info"></i> Support
</a>
</p>
</section>
</main>
</body>
</html>`;
/**
* Starts up a web server for health monitoring.
*/
export const instantiateServer = (): void => {
try {
const server = fastify({
logger: false,
});
server.get("/", (_request, response) => {
response.header("Content-Type", "text/html");
response.send(html);
});
server.listen({ port: 5011 }, (error) => {
if (error) {
void logger.error("instantiate server", error);
return;
}
void logger.log("debug", "Server listening on port 5011.");
});
} catch (error) {
if (error instanceof Error) {
void logger.error("instantiate server", error);
return;
}
void logger.error("instantiate server", new Error(String(error)));
}
};

15
src/utils/ai.ts Normal file
View File

@ -0,0 +1,15 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
// eslint-disable-next-line @typescript-eslint/naming-convention -- Importing a class.
import Anthropic from "@anthropic-ai/sdk";
/**
* The Anthropic AI instance.
*/
export const ai = new Anthropic({
apiKey: process.env.AI_TOKEN,
});

View File

@ -0,0 +1,31 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { logger } from "./logger.js";
import type { Usage } from "@anthropic-ai/sdk/resources/index.js";
/**
* Calculates the cost of a command run by a user, and sends to
* our logging service.
* @param usage -- The usage payload from Anthropic.
* @param uuid -- The Discord ID of the user who ran the command.
*/
export const calculateCost = async(
usage: Usage,
uuid: string,
): Promise<void> => {
const inputCost = usage.input_tokens * (3 / 1_000_000);
const outputCost = usage.output_tokens * (15 / 1_000_000);
const totalCost = inputCost + outputCost;
await logger.log(
"info",
`User ${uuid} used the bot, which accepted ${usage.input_tokens.toString()} and generated ${usage.output_tokens.toString()}.
Total cost: ${totalCost.toLocaleString("en-GB", {
currency: "USD",
style: "currency",
})}`,
);
};

78
src/utils/isSubscribed.ts Normal file
View File

@ -0,0 +1,78 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
type ChatInputCommandInteraction,
type Message,
} from "discord.js";
/**
* Checks if a user has an active entitlement (subscription) for the bot.
* If they do not, it responds to the interaction with a button to subscribe.
* @param interaction -- The interaction payload from Discord.
* @returns A boolean indicating whether the user is subscribed.
*/
const isSubscribedInteraction = async(
interaction: ChatInputCommandInteraction,
): Promise<boolean> => {
const isEntitled = interaction.entitlements.find((entitlement) => {
return entitlement.userId === interaction.user.id && entitlement.isActive();
});
if (!isEntitled && interaction.user.id !== "465650873650118659") {
const subscribeButton = new ButtonBuilder().
setStyle(ButtonStyle.Premium).
setSKUId("1343379640424857711");
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(
subscribeButton,
);
await interaction.editReply({
components: [ row ],
content: "You must be subscribed to use this feature.",
});
return false;
}
return true;
};
/**
* Checks if a user has an active entitlement (subscription) for the bot.
* If they do not, it responds to the message with a button to subscribe.
* @param message -- The message payload from Discord.
* @returns A boolean indicating whether the user is subscribed.
*/
const isSubscribedMessage = async(
message: Message,
): Promise<boolean> => {
if (message.author.id === "465650873650118659") {
return true;
}
const subscribeButton = new ButtonBuilder().
setStyle(ButtonStyle.Premium).
setSKUId("1343379640424857711");
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(
subscribeButton,
);
await message.client.application.entitlements.fetch();
const isEntitled = message.client.application.entitlements.cache.find(
(entitlement) => {
return entitlement.userId === message.author.id && entitlement.isActive();
},
);
if (!isEntitled) {
await message.reply({
components: [ row ],
content: "You must be subscribed to use this feature.",
});
return false;
}
return true;
};
export { isSubscribedInteraction, isSubscribedMessage };

12
src/utils/logger.ts Normal file
View File

@ -0,0 +1,12 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import { Logger } from "@nhcarrigan/logger";
export const logger = new Logger(
"Maylin Taryne",
process.env.LOG_TOKEN ?? "",
);

39
src/utils/replyToError.ts Normal file
View File

@ -0,0 +1,39 @@
/**
* @copyright nhcarrigan
* @license Naomi's Public License
* @author Naomi Carrigan
*/
import {
ActionRowBuilder,
ButtonBuilder,
ButtonStyle,
type ChatInputCommandInteraction,
type MessageContextMenuCommandInteraction,
} from "discord.js";
/**
* Responds to an interaction with a generic error message.
* @param interaction -- The interaction payload from Discord.
*/
export const replyToError = async(
interaction:
| ChatInputCommandInteraction
| MessageContextMenuCommandInteraction,
): Promise<void> => {
const button = new ButtonBuilder().
setLabel("Need help?").
setStyle(ButtonStyle.Link).
setURL("https://chat.nhcarrigan.com");
const row = new ActionRowBuilder<ButtonBuilder>().addComponents(button);
if (interaction.deferred || interaction.replied) {
await interaction.editReply({
components: [ row ],
content: "Something went wrong with this command.",
});
return;
}
await interaction.reply({
components: [ row ],
content: "Something went wrong with this command.",
});
};

8
tsconfig.json Normal file
View File

@ -0,0 +1,8 @@
{
"extends": "@nhcarrigan/typescript-config",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./prod"
},
"exclude": ["test/**/*.ts", "vitest.config.ts"]
}

15
vitest.config.ts Normal file
View File

@ -0,0 +1,15 @@
import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
coverage: {
provider: "istanbul",
reporter: ["text", "html"],
all: true,
allowExternal: true,
thresholds: {
lines: 0,
},
},
},
});