SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
add mw module
Ahmed Essamd747ef081635
diff --git a/packages/middleware/.eslintrc.json b/packages/middleware/.eslintrc.jsonnew file mode 100644index 00000000..eec085fd--- /dev/null+++ b/packages/middleware/.eslintrc.json@@ -0,0 +1,63 @@+{+ "env": {+ "node": true,+ "es2021": true,+ "jest": true+ },+ "extends": ["airbnb-base", "prettier", "plugin:@typescript-eslint/recommended", "plugin:prettier/recommended"],+ "globals": {+ "NodeJS": true+ },+ "parser": "@typescript-eslint/parser",+ "parserOptions": {+ "ecmaVersion": 12,+ "sourceType": "module"+ },+ "plugins": ["@typescript-eslint", "import"],++ "rules": {+ "import/prefer-default-export": "off",+ "class-methods-use-this": "off",+ "@typescript-eslint/no-non-null-assertion": "off",+ "no-underscore-dangle": "off",+ "import/no-relative-packages": "off",+ "import/no-extraneous-dependencies": "off",+ "consistent-return": "off",+ "no-plusplus": "off",+ "eqeqeq": "off",+ "import/extensions": "off",+ "import/no-unresolved": "off",+ "lines-between-class-members": "off",+ "no-continue": "off",+ "no-use-before-define": "off",+ "no-restricted-syntax": "off",+ "no-unused-vars": "off",+ "@typescript-eslint/ban-types": "off",+ "no-await-in-loop": "off",+ "no-else-return": "off",+ "no-nested-ternary": "off",+ "no-extra-boolean-cast": "off",+ "@typescript-eslint/no-unused-vars": [+ "warn", // or "error"+ {+ "argsIgnorePattern": "^_",+ "varsIgnorePattern": "^_",+ "caughtErrorsIgnorePattern": "^_"+ }+ ],+ "@typescript-eslint/no-explicit-any": ["off"],+ "import/order": ["off"],+ "@typescript-eslint/ban-ts-comment": ["off"],+ "prefer-destructuring": ["off"],+ "no-shadow": ["off"]+ },+ "settings": {+ "import/resolver": {+ "node": {+ "paths": ["src"],+ "extensions": [".js", ".ts", ".d.ts", ".tsx"]+ }+ }+ },+ "ignorePatterns": ["*.d.ts"]+}diff --git a/packages/middleware/.gitignore b/packages/middleware/.gitignorenew file mode 100644index 00000000..84b55c3a--- /dev/null+++ b/packages/middleware/.gitignore@@ -0,0 +1,136 @@+# 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++# 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.*+++**/*_test.ts+++# prisma generated files+prisma*/generated/\ No newline at end of filediff --git a/packages/middleware/.lintstagedrc.json b/packages/middleware/.lintstagedrc.jsonnew file mode 100644index 00000000..fe275acd--- /dev/null+++ b/packages/middleware/.lintstagedrc.json@@ -0,0 +1,3 @@+{+ "*.ts": "eslint"+}diff --git a/packages/middleware/.prettierignore b/packages/middleware/.prettierignorenew file mode 100644index 00000000..9f9fd175--- /dev/null+++ b/packages/middleware/.prettierignore@@ -0,0 +1,41 @@+# Ignore node_modules directory+node_modules++# Ignore build output directories+dist+build++# Ignore coverage reports+coverage++# Ignore logs and temporary files+*.log+*.tmp++# Ignore compiled files+*.min.js+*.min.css++# Ignore package lock files+package-lock.json+yarn.lock++# Ignore editor and IDE specific files+.vscode+.idea+*.sublime-project+*.sublime-workspace++# Ignore configuration files+*.config.js+*.config.json++# Ignore git related files+.git+.gitignore+.gitattributes+.gitkeep++# Ignore Docker files+Dockerfile+docker-compose.ymldiff --git a/packages/middleware/.prettierrc.json b/packages/middleware/.prettierrc.jsonnew file mode 100644index 00000000..313081be--- /dev/null+++ b/packages/middleware/.prettierrc.json@@ -0,0 +1,8 @@+{+ "printWidth": 150,+ "singleQuote": true,+ "trailingComma": "all",+ "bracketSpacing": true,+ "arrowParens": "avoid",+ "endOfLine": "auto"+}diff --git a/packages/middleware/README.md b/packages/middleware/README.mdnew file mode 100644index 00000000..5935bd7f--- /dev/null+++ b/packages/middleware/README.md@@ -0,0 +1 @@+# smyth-middleware\ No newline at end of filediff --git a/packages/middleware/_automation/commands/create-module.sh b/packages/middleware/_automation/commands/create-module.shnew file mode 100644index 00000000..eb9ee4a7--- /dev/null+++ b/packages/middleware/_automation/commands/create-module.sh@@ -0,0 +1,30 @@+#!/bin/bash++# Get the project root dynamically+root=$(git rev-parse --show-toplevel)++# Check if the root/modules directory exists, if not create it+modules_dir="$root/src/modules"+if [ ! -d "$modules_dir" ]; then+ mkdir "$modules_dir"+fi++# Check if -h flag was passed+if [ "$1" = "-h" ]; then+ echo "This script creates a new module in the project."+ echo "Usage: create-module.sh [module_name]"+ exit 0+fi++# Get the name from the command line argument+name="$1"++# Create the directory with the given name inside the modules directory+module_dir="$modules_dir/$name"+mkdir "$module_dir"++# Create the required empty directories inside the module directory+mkdir "$module_dir/services"+mkdir "$module_dir/utils"+mkdir "$module_dir/controllers"+mkdir "$module_dir/routers"diff --git a/packages/middleware/config/config.ts b/packages/middleware/config/config.tsnew file mode 100644index 00000000..ab95de3a--- /dev/null+++ b/packages/middleware/config/config.ts@@ -0,0 +1,50 @@+/* eslint-disable @typescript-eslint/no-non-null-assertion */+import expandEnv from 'dotenv-expand';+import dotenvFlow from 'dotenv-flow';+import os from 'os';+import path from 'path';+import { name, version } from '../package.json';+import { getDirname } from '../src/utils/general';++expandEnv.expand(+ dotenvFlow.config({+ files: ['../../.env', '../.env'],+ }),+);++// const rootPath = require.main?.path;+const rootPath = path.join(getDirname(), '..');++if (!rootPath) {+ process.exit(1);+}++const getLocalStoragePath = () => {+ const homeDir = os.homedir();+ return path.join(homeDir, 'smythos-data');+};++const LOCAL_STORAGE_PATH = getLocalStoragePath();++// Default to SQLite if no DATABASE_URL is provided (not working yet)++export const config = {+ variables: {+ env: process.env.NODE_ENV,+ port: process.env.MIDDLEWARE_API_PORT,++ DATABASE_PROVIDER: process.env.DATABASE_PROVIDER,+ DATABASE_HOST: process.env.DATABASE_HOST,+ DATABASE_USER: process.env.DATABASE_USER,+ DATABASE_PASSWORD: process.env.DATABASE_PASSWORD,+ DATABASE_NAME: process.env.DATABASE_NAME,+ DATABASE_URL: process.env.DATABASE_URL,+ LOCAL_STORAGE_PATH,+ SRE_STORAGE_PATH: path.join(LOCAL_STORAGE_PATH, '.smyth'),+ },++ package: {+ name,+ version,+ },+};diff --git a/packages/middleware/config/logging-v2.ts b/packages/middleware/config/logging-v2.tsnew file mode 100644index 00000000..fb7e0e85--- /dev/null+++ b/packages/middleware/config/logging-v2.ts@@ -0,0 +1,168 @@+/* eslint-disable no-useless-constructor */+/* eslint-disable max-classes-per-file */+import winston from 'winston';+import Transport from 'winston-transport';++winston.addColors({+ error: 'red',+ warn: 'yellow',+ info: 'green',+ debug: 'blue',+});++// Retrieve the DEBUG environment variable and split it into an array of namespaces+const namespaces = (process.env.LOG_FILTER || '').split(',');++// Create a Winston format that filters messages based on namespaces+const namespaceFilter = winston.format(info => {+ // If DEBUG is not set, log everything+ if (!process.env.LOG_FILTER || namespaces.some(ns => (info.module as string)?.includes(ns))) {+ return info;+ }+ return false; // Filter out messages that do not match the namespace+})();++// Custom stream for your transport+class ArrayTransport extends Transport {+ private logs: any[];+ constructor(opts: winston.transport.TransportStreamOptions | undefined) {+ super(opts);+ // Configure your storage array+ this.logs = (opts as any)?.logs || [];+ }++ log(info: { level: any; message: any }, callback: () => void) {+ setImmediate(() => {+ this.emit('logged', info);+ });++ // Perform the writing to the array storage+ this.logs.push(`${info.level}: ${info.message}`);++ // Perform the writing to the remote service+ callback();+ }+}++class Logger {+ public startTime = Date.now();+ public get output() {+ return Array.isArray(this.data) ? this.data.join('\n') : undefined;+ }+ public get elapsedTime() {+ return Date.now() - this.startTime;+ }+ constructor(private _logger: winston.Logger, public data: any[] | undefined, private labels: { [key: string]: any }) {}++ public log(...args: any[]) {+ this._logger.log('info', formatLogMessage(...args), this.labels);+ }+ public warn(...args: any[]) {+ this._logger.log('warn', formatLogMessage(...args), this.labels);+ }+ public debug(...args: any[]) {+ this._logger.log('debug', formatLogMessage(...args), this.labels);+ }+ public info(...args: any[]) {+ this._logger.log('info', formatLogMessage(...args), this.labels);+ }+ public verbose(...args: any[]) {+ this._logger.log('verbose', formatLogMessage(...args), this.labels);+ }++ public error(...args: any[]) {+ const stack = new Error().stack;++ this._logger.log('error', formatLogMessage(...args), { ...this.labels, stack });+ }+}++const MAX_LOG_MESSAGE_LENGTH = 500;++function createBaseLogger(memoryStore?: any[]) {+ const logger = winston.createLogger({+ // level: 'info', // log level++ format: winston.format.combine(+ winston.format.timestamp(),+ winston.format.errors({+ stack: true,+ }),+ winston.format.splat(),+ winston.format.json(),+ ),++ transports: [+ new winston.transports.Console({+ level: 'error',+ // handleExceptions: true,+ format: winston.format.combine(+ winston.format.printf(info => {+ let message = info.message;+ message =+ (message as string)?.length > MAX_LOG_MESSAGE_LENGTH ? `${(message as string).substring(0, MAX_LOG_MESSAGE_LENGTH)}...` : message;+ return `${info.level}:${info.module || ''} ${message} ${info.stack || ''}`;+ }),+ ),+ stderrLevels: ['error'], // Define levels that should be logged to stderr+ }),+ new winston.transports.Console({+ level: process.env.LOG_LEVEL || 'info',+ format: winston.format.combine(+ namespaceFilter,+ winston.format.printf(info => {+ const module = info.module ? winston.format.colorize().colorize(info.level, ` [${info.module}]`) : '';+ const ns = winston.format.colorize().colorize(info.level, `${info.level}${module}`);++ let message = info.message;+ message =+ (message as string)?.length > MAX_LOG_MESSAGE_LENGTH ? `${(message as string).substring(0, MAX_LOG_MESSAGE_LENGTH)}...` : message;++ return `${ns} - ${message}`;+ }),+ ),++ // handleExceptions: true,+ }),+ ],+ });++ if (Array.isArray(memoryStore)) {+ logger.add(+ new ArrayTransport({+ level: 'debug',+ // @ts-ignore+ logs: memoryStore,+ }),+ );+ }++ return logger;+}++function formatLogMessage(...args: any[]) {+ return args+ .map(arg => {+ // If the argument is an object (and not null), serialize it to JSON+ if (typeof arg === 'object' && arg !== null && !(arg instanceof Error)) {+ return JSON.stringify(arg, null, 2); // set the space to 2 for better readability+ }+ // Otherwise, just convert it to a string in case it's not+ return String(arg);+ })+ .join(' '); // Concatenate all arguments with a space+}++function createLabeledLogger(labels: { [key: string]: any }, memoryStore?: any[]) {+ const _logger = createBaseLogger(memoryStore);++ _logger.defaultMeta = labels;++ const logger = new Logger(_logger, memoryStore, labels);++ return logger;+}++export function createLogger(module: string, withMemoryStore = false) {+ return createLabeledLogger({ module }, withMemoryStore ? [] : undefined);+}diff --git a/packages/middleware/config/logging.ts b/packages/middleware/config/logging.tsnew file mode 100644index 00000000..d3b2ab5b--- /dev/null+++ b/packages/middleware/config/logging.ts@@ -0,0 +1,40 @@+import winston from 'winston';++function createBaseLogger() {+ return winston.createLogger({+ level: 'info', // log level++ format: winston.format.combine(+ winston.format.timestamp(),+ winston.format.errors({+ stack: true,+ }),+ winston.format.splat(),+ winston.format.json(),+ ),++ transports: [+ new winston.transports.Console({+ format: winston.format.combine(+ winston.format.colorize(),+ winston.format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`),+ ),+ }),+ ],+ });+}++const createLabeledLogger = (labels: { [key: string]: string }) => {+ const logger = createBaseLogger();++ logger.defaultMeta = labels;++ return logger;+};++const LOGGER = createBaseLogger();+LOGGER.on('error', err => {+ console.error(err);+});++export { createLabeledLogger, LOGGER };diff --git a/packages/middleware/docs/_sysapi.swagger.json b/packages/middleware/docs/_sysapi.swagger.jsonnew file mode 100644index 00000000..75070d8b--- /dev/null+++ b/packages/middleware/docs/_sysapi.swagger.json@@ -0,0 +1,3199 @@+{+ "swagger": "2.0",+ "info": {+ "description": "Smyth API Machine Endpoints",+ "version": "1.0.0",+ "title": "Smyth API M2M",+ "basePath": "/_sysapi/v1",+ "license": {+ "name": "MIT License",+ "url": "https://opensource.org/licenses/MIT"+ }+ },+ "basePath": "/_sysapi/v1",+ "schemes": ["https", "http"],+ "produces": ["application/json"],+ "consumes": ["application/json"],+ "securityDefinitions": {+ "Bearer": {+ "description": "For accessing the protected API resources, you must have received a valid token after registering or logging in. This JWT token must then be used for all protected resources by passing it in via the 'Authorization' header.\n\nA JWT token is generated by the API by either registering via /users or logging in via /users/login. The following format must be in the 'Authorization' header :\n\n Token: xxxxxx.yyyyyyy.zzzzzz\n",+ "type": "apiKey",+ "name": "Authorization",+ "in": "header"+ }+ },++ "paths": {+ "/ai-agent/{agentId}": {+ "get": {+ "tags": ["Agents"],+ "summary": "Get agent",+ "description": "Get agent",+ "operationId": "getAgent",+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "include",+ "in": "query",+ "description": "extended data",+ "required": false,+ "type": "array"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent": {+ "get": {+ "tags": ["Agents"],+ "summary": "Get agent by domain name",+ "description": "Get agent by Domain name",+ "operationId": "getAgentByDomain",+ "parameters": [+ {+ "name": "domainName",+ "in": "query",+ "description": "domain name linked to agent",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "produces": ["application/json"],++ "security": [+ {+ "Bearer": []+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/Agent"+ }+ }+ }+ }+ },++ "/ai-agent/teams/{teamId}": {+ "get": {+ "tags": ["Agents"],+ "summary": "Get team agents",+ "description": "Get all agents that belong to a specific team. Returns only agents directly owned by the team (no subteam agents).",+ "operationId": "getTeamAgents",+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team ID",+ "required": true,+ "type": "string"+ },+ {+ "name": "deployedOnly",+ "in": "query",+ "description": "If true, returns only agents that have at least one deployment",+ "required": false,+ "type": "boolean",+ "default": false+ },+ {+ "name": "includeData",+ "in": "query",+ "description": "If true, returns agent data",+ "required": false,+ "type": "boolean",+ "default": false+ },+ {+ "name": "page",+ "in": "query",+ "description": "Page number for pagination",+ "required": false,+ "type": "integer",+ "minimum": 1+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Number of items per page",+ "required": false,+ "type": "integer",+ "minimum": 1+ }+ ],+ "produces": ["application/json"],+ "responses": {+ "200": {+ "description": "List of agents belonging to the team",+ "schema": {+ "type": "object",+ "properties": {+ "agents": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "deployed": {+ "type": "boolean",+ "description": "Indicates if the agent has any deployments"+ },+ "domain": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "verified": {+ "type": "boolean"+ },+ "lastStatus": {+ "type": "string"+ }+ }+ },+ "createdAt": {+ "type": "string",+ "format": "date-time"+ },+ "updatedAt": {+ "type": "string",+ "format": "date-time"+ }+ }+ }+ },+ "total": {+ "type": "integer",+ "description": "Total number of agents matching the query"+ }+ }+ }+ },+ "400": {+ "description": "Invalid request parameters",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ },+ "404": {+ "description": "Team not found",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/ai-agent/{agentId}/settings": {+ "get": {+ "tags": ["Agent Settings"],+ "summary": "Get settings",+ "description": "Get settings",+ "operationId": "getAgentSettings",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/{agentId}/deployments": {+ "get": {+ "tags": ["Agent Deployments"],+ "summary": "Get agent deployments",+ "description": "Get agent deployments",+ "operationId": "getAgentDeployments",+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "agent deployments",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/ai-agent/{agentId}/deployments/{majorVersion}/{minorVersion}": {+ "get": {+ "tags": ["Agent Deployments"],+ "summary": "Get agent deployments by version",+ "description": "Get agent deployments by version",+ "operationId": "getAgentDeploymentsByVersion",+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "majorVersion",+ "in": "path",+ "description": "Major version",+ "required": true,+ "type": "string"+ },+ {+ "name": "minorVersion",+ "in": "path",+ "description": "Minor version",+ "required": true,+ "type": "string"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "agent deployments",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/deployments/{deploymentId}": {+ "get": {+ "tags": ["Agent Deployments"],+ "summary": "Get agent deployment",+ "description": "Get agent deployment",+ "operationId": "getAgentDeployment",+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "deploymentId",+ "in": "path",+ "description": "Deployment id",+ "required": true,+ "type": "string"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "agent deployment",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/{agentId}/states": {+ "get": {+ "tags": ["Agent States"],+ "summary": "Get agent states",+ "description": "get agent states",+ "operationId": "getAgentStates",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "put": {+ "tags": ["Agent States"],+ "summary": "Create/Update agent state",+ "description": "create agent state",+ "operationId": "createAgentState",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing agent state data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "key": {+ "type": "string"+ },+ "value": {+ "type": "string"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/{agentId}/states/{key}": {+ "get": {+ "tags": ["Agent States"],+ "summary": "Get agent state",+ "description": "get agent state by key name",+ "operationId": "getAgentState",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "key",+ "in": "path",+ "description": "Key name",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "delete": {+ "tags": ["Agent States"],+ "summary": "Delete agent state",+ "description": "Delete agent state by key name",+ "operationId": "deleteAgentState",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "key",+ "in": "path",+ "description": "Key name",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/{agentId}/logs/calls": {+ "post": {+ "tags": ["Agent Logs"],+ "summary": "Create agent call log",+ "description": "Create agent call log",+ "operationId": "createAgentCallLog",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ },++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing settings data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "sourceId": {+ "type": "string"+ },+ "componentId": {+ "type": "string"+ },+ "input": {+ "type": "object"+ },+ "output": {+ "type": "object"+ },+ "inputTimestamp": {+ "type": "string"+ },+ "outputTimestamp": {+ "type": "string"+ },+ "domain": {+ "type": "string"+ },+ "result": {+ "type": "string"+ },+ "error": {+ "type": "string"+ },+ "inputTokens": {+ "type": "number"+ },+ "outputTokens": {+ "type": "number"+ },+ "sourceName": {+ "type": "string"+ },+ "componentName": {+ "type": "string"+ },+ "sessionID": {+ "type": "string"+ },+ "workflowID": {+ "type": "string"+ },+ "processID": {+ "type": "string"+ },+ "tags": {+ "type": "string"+ }+ }+ }+ }+ ]+ }+ },++ "/ai-agent/logs/calls/{callId}": {+ "put": {+ "tags": ["Agent Logs"],+ "summary": "Update agent call log",+ "description": "Update agent call log",+ "operationId": "updateAgentCallLog",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ },++ "parameters": [+ {+ "name": "callId",+ "in": "path",+ "description": "Call id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing settings data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "sourceId": {+ "type": "string"+ },+ "componentId": {+ "type": "string"+ },+ "domain": {+ "type": "string"+ },+ "input": {+ "type": "object"+ },+ "output": {+ "type": "object"+ },+ "inputTimestamp": {+ "type": "string"+ },+ "outputTimestamp": {+ "type": "string"+ },+ "result": {+ "type": "string"+ },+ "error": {+ "type": "string"+ },+ "inputTokens": {+ "type": "number"+ },+ "outputTokens": {+ "type": "number"+ },+ "sourceName": {+ "type": "string"+ },+ "componentName": {+ "type": "string"+ },+ "sessionID": {+ "type": "string"+ },+ "workflowID": {+ "type": "string"+ },+ "processID": {+ "type": "string"+ },+ "tags": {+ "type": "string"+ }+ }+ }+ }+ ]+ }+ },++ "/chats": {+ "post": {+ "tags": ["Chats"],+ "summary": "Create conversation",+ "description": "Create conversation",+ "operationId": "createConversation",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing conversation data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "conversation": {+ "type": "object",+ "properties": {+ "label": {+ "type": "string",+ "default": ""+ },+ "summary": {+ "type": "string",+ "default": ""+ },+ "teamId": {+ "type": "string"+ },+ "ownerId": {+ "type": "number",+ "default": null+ },+ "aiAgentId": {+ "type": "string"+ },+ "chunkSize": {+ "type": "number",+ "default": null+ },+ "lastChunkID": {+ "type": "string",+ "default": null+ }+ }+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "get": {+ "tags": ["Chats"],+ "summary": "Get all conversations",+ "description": "Get all conversations",+ "operationId": "getConversations",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [+ {+ "name": "agentId",+ "in": "query",+ "description": "Agent ID",+ "required": false,+ "type": "string"+ },+ {+ "name": "ownerId",+ "in": "query",+ "description": "Owner ID",+ "required": false,+ "type": "number"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful operation",+ "schema": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "conversationId": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "summary": {+ "type": "string"+ },+ "teamId": {+ "type": "string"+ },+ "ownerId": {+ "type": "number"+ },+ "aiAgentId": {+ "type": "string"+ },+ "chunkSize": {+ "type": "number"+ },+ "lastChunkID": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ }+ },++ "/chats/{conversationId}": {+ "get": {+ "tags": ["Chats"],+ "summary": "Get conversation by ID",+ "description": "Get conversation by ID",+ "operationId": "getConversationById",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [+ {+ "name": "conversationId",+ "in": "path",+ "description": "Conversation ID",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful operation",+ "schema": {+ "type": "object",+ "properties": {+ "conversationId": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "summary": {+ "type": "string"+ },+ "teamId": {+ "type": "string"+ },+ "ownerId": {+ "type": "number"+ },+ "aiAgentId": {+ "type": "string"+ },+ "chunkSize": {+ "type": "number"+ },+ "lastChunkID": {+ "type": "string"+ }+ }+ }+ }+ }+ },+ "put": {+ "tags": ["Chats"],+ "summary": "Update conversation",+ "description": "Update conversation",+ "operationId": "updateConversation",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [+ {+ "name": "conversationId",+ "in": "path",+ "description": "Conversation ID",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing conversation data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "conversation": {+ "type": "object",+ "properties": {+ "aiAgentId": {+ "type": "string",+ "default": null+ },+ "ownerId": {+ "type": "number",+ "default": null+ },+ "chunkSize": {+ "type": "number",+ "default": null+ },+ "lastChunkID": {+ "type": "string",+ "default": null+ },+ "label": {+ "type": "string",+ "default": null+ },+ "summary": {+ "type": "string",+ "default": null+ }+ }+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "delete": {+ "tags": ["Chats"],+ "summary": "Delete conversation",+ "description": "Delete conversation",+ "operationId": "deleteConversation",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [+ {+ "name": "conversationId",+ "in": "path",+ "description": "Conversation ID",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams": {+ "get": {+ "tags": ["Teams"],+ "summary": "Get all teams",+ "description": "Get all teams",+ "operationId": "getTeams",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [+ {+ "name": "page",+ "in": "query",+ "description": "Page number",+ "required": false,+ "type": "integer"+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Number of results per page",+ "required": false,+ "type": "integer"+ }+ ],++ "responses": {+ "200": {+ "description": "teams",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/{teamId}": {+ "get": {+ "tags": ["Teams"],+ "summary": "Get a team",+ "description": "Get a team",+ "operationId": "getTeamById",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "team",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/{teamId}/settings": {+ "get": {+ "tags": ["Team Settings"],+ "summary": "Get team settings",+ "description": "Get team settings",+ "operationId": "getTeamSettings",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "Team settings",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "put": {+ "tags": ["Team Settings"],+ "summary": "Create/Update team settings",+ "description": "Update team settings",+ "operationId": "updateTeamSettings",+ "produces": ["application/json"],++ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing settings data",+ "required": true,+ "schema": {+ "$ref": "#/definitions/SettingsRequest"+ }+ }+ ],+ "security": [+ {+ "Bearer": []+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/{teamId}/settings/{settingKey}": {+ "get": {+ "tags": ["Team Settings"],+ "summary": "Get team setting",+ "description": "Get team setting",+ "operationId": "getTeamSetting",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team id",+ "required": true,+ "type": "string"+ },+ {+ "name": "settingKey",+ "in": "path",+ "description": "Setting key",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "Team setting",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "delete": {+ "tags": ["Team Settings"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "summary": "Delete team setting",+ "description": "Delete team setting",+ "operationId": "deleteTeamSetting",+ "produces": ["application/json"],++ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team id",+ "required": true,+ "type": "string"+ },+ {+ "name": "settingKey",+ "in": "path",+ "description": "Setting key",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vectors/namespaces/search": {+ "get": {+ "tags": ["Vectors"],+ "summary": "Query Namespace",+ "description": "Run similarity search on a namespace.",+ "operationId": "runSimilaritySearch",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [+ {+ "name": "query",+ "in": "query",+ "description": "Query",+ "required": true,+ "type": "string"+ },+ {+ "name": "raw",+ "in": "query",+ "description": "Include metadata",+ "required": false,+ "type": "boolean"+ },+ {+ "name": "topK",+ "in": "query",+ "description": "Number of results",+ "required": true,+ "type": "integer"+ },+ {+ "name": "namespaceId",+ "in": "query",+ "description": "Namespace Id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vectors/namespaces": {+ "get": {+ "tags": ["Vectors"],+ "summary": "Get all namespaces",+ "description": "Get all namespaces",+ "operationId": "getNamespaces",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [+ {+ "name": "teamId",+ "in": "query",+ "description": "Team id",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "Namespaces",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "post": {+ "tags": ["Vectors"],+ "summary": "Create namespace",+ "description": "Create namespace",+ "operationId": "createNamespace",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Namespace data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "teamId": {+ "type": "string"+ },+ "useCustomVectorStorage": {+ "type": "boolean"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Namespace created",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vectors/namespaces/{namespaceId}": {+ "get": {+ "tags": ["Vectors"],+ "summary": "Get Namespace",+ "description": "Get Namespace",+ "operationId": "getNamespace",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [+ {+ "name": "namespaceId",+ "in": "path",+ "description": "Namespace Id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "Namespace ownership",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "delete": {+ "tags": ["Vectors"],+ "summary": "Delete namespace",+ "description": "Delete namespace",+ "operationId": "deleteNamespace",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [+ {+ "name": "namespaceId",+ "in": "path",+ "description": "Namespace Id",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "Namespace deleted",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vectors/datasources": {+ "get": {+ "tags": ["Vectors"],+ "summary": "Get all datasources",+ "description": "Get all datasources",+ "operationId": "getDatasources",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [+ {+ "name": "namespaceId",+ "in": "query",+ "description": "Namespace Id",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "Datasources",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "post": {+ "tags": ["Vectors"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "summary": "Add datasource",+ "description": "Add vector datasource",+ "operationId": "addDatasource",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Datasource data. for 'type' field, please refer to 'DatasourceType' model at the bottom of the page",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "teamId": {+ "type": "string"+ },+ "type": {+ "type": "string",+ "enum": ["SITEMAP", "PDF", "WORD", "WEBPAGE"]+ },+ "name": {+ "type": "string"+ },+ "url": {+ "type": "string"+ },+ "namespaceId": {+ "type": "string"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid request data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/vectors/datasources/text": {+ "post": {+ "tags": ["Vectors"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "summary": "Add datasource text",+ "description": "Add vector datasource text",+ "operationId": "addDatasourceText",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Datasource data. for 'type' field, please refer to 'DatasourceType' model at the bottom of the page",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "text": {+ "type": "string"+ },+ "namespaceId": {+ "type": "string"+ },+ "teamId": {+ "type": "string"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid request data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/vectors/datasources/{datasourceId}": {+ "get": {+ "tags": ["Vectors"],+ "summary": "Get datasource",+ "description": "Get datasource",+ "operationId": "getDatasource",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "datasourceId",+ "in": "path",+ "description": "Datasource id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "Datasource data",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid request data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ },+ "delete": {+ "tags": ["Vectors"],+ "summary": "Delete datasource",+ "description": "Delete datasource",+ "operationId": "deleteDatasource",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "datasourceId",+ "in": "path",+ "description": "Datasource id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "Datasource data",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid request data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/domains": {+ "get": {+ "tags": ["Domains"],+ "summary": "Get all domains",+ "description": "Get all domains [M2M allowed]",+ "operationId": "getDomains",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "verified",+ "in": "query",+ "description": "Domain Status",+ "required": false,+ "type": "boolean"+ },+ {+ "name": "name",+ "in": "query",+ "description": "Domain name",+ "required": false,+ "type": "string"+ },+ {+ "name": "aiAgentId",+ "in": "query",+ "description": "Attached agent id",+ "required": false,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid request",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/domain/query": {+ "post": {+ "tags": ["Domains"],+ "summary": "Query Domain by name",+ "description": "Query Domain by name [M2M allowed]",+ "operationId": "queryDomain",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing domain data",+ "required": true,+ "schema": {+ "$ref": "#/definitions/Domain"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid domain data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ },+ "404": {+ "description": "Domain not found",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/embodiments": {+ "get": {+ "tags": ["Embodiments"],+ "summary": "Get all embodiments by agent id",+ "description": "Get all embodiments by agent id",+ "operationId": "getEmbodiments",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "aiAgentId",+ "in": "query",+ "description": "Agent Id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "type": "object",+ "properties": {+ "embodiments": {+ "type": "object"+ }+ }+ }+ }+ }+ }+ },++ "/subscriptions/teams": {+ "post": {+ "tags": ["Subscriptions"],+ "summary": "Create a subscription for a team.",+ "description": "Create a subscription for a team. If the team already has a subs, it will delete the current and replace it with the new one",+ "operationId": "createTeamSubs",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing job data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "teamId": {+ "type": "string"+ },++ "stripeSubsId": {+ "type": "string"+ },++ "planName": {+ "type": "string"+ },++ "planPrice": {+ "type": "number"+ },++ "stripeProductId": {+ "type": "string"+ },++ "stripePriceId": {+ "type": "string"+ },++ "planLimits": {+ "type": "object",+ "schema": {+ "properties": {+ "prodAiAgents": {+ "type": "number"+ },+ "devAiAgents": {+ "type": "number"+ },+ "teamMembers": {+ "type": "number"+ }+ }+ }+ },++ "featureFlags": {+ "type": "object",+ "schema": {+ "properties": {+ "embodimentsEnabled": {+ "type": "boolean"+ },+ "agentAuthSidebarEnabled": {+ "type": "boolean"+ },+ "domainRegistrationEnabled": {+ "type": "boolean"+ }+ }+ }+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ },++ "examples": {+ "application/json": {+ "teamId": "clnew8cjb000p234m02kvf8r6q",+ "stripeSubsId": "sub_1",+ "planName": "Free",+ "planPrice": 0,+ "stripeProductId": "prod_1",+ "stripePriceId": "price_1",+ "planLimits": {+ "prodAiAgents": 50,+ "devAiAgents": 100,+ "teamMembers": 5+ },+ "featureFlags": {+ "embodimentsEnabled": true,+ "agentAuthSidebarEnabled": true,+ "domainRegistrationEnabled": true+ }+ }+ }+ },+ "400": {+ "description": "Invalid job data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/subscriptions/teams/{teamId}": {+ "put": {+ "tags": ["Subscriptions"],+ "summary": "Edit team subscription",+ "description": "Edit team subscriptionm",+ "operationId": "editTeamSubs",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "team id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing job data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "stripeSubsId": {+ "type": "string"+ },++ "properties": {+ "type": "object",+ "schema": {+ "properties": {+ "tasks": {+ "type": "number"+ }+ }+ }+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid job data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ },++ "get": {+ "tags": ["Subscriptions"],+ "summary": "Get team subscription by team id",+ "description": "Get team subscription",+ "operationId": "getTeamSubs",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "team id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "type": "object",+ "properties": {+ "embodiments": {+ "type": "object"+ }+ }+ }+ }+ }+ },++ "delete": {+ "tags": ["Subscriptions"],+ "summary": "delete team subscription",+ "description": "delete team subscription",+ "operationId": "deleteTeamSubs",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "team id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/subscriptions/teams/{teamId}/plan/{planId}": {+ "post": {+ "tags": ["Subscriptions"],+ "summary": "Create a team subscription linked to an exising plan",+ "description": "Change team subscription plan to an existing plan",+ "operationId": "changeTeamSubsPlan",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "team id",+ "required": true,+ "type": "string"+ },+ {+ "name": "planId",+ "in": "path",+ "description": "plan id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing job data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "stripeSubsId": {+ "type": "string"+ },+ "properties": {+ "type": "object",+ "schema": {+ "properties": {+ "tasks": {+ "type": "number"+ }+ }+ }+ },++ "endAt": {+ "type": "string"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "type": "object",+ "properties": {+ "embodiments": {+ "type": "object"+ }+ }+ }+ }+ }+ }+ },++ "/plans": {+ "post": {+ "tags": ["Plans"],+ "summary": "Create a plan",+ "description": "Create a plan",+ "operationId": "createPlan",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing job data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "planName": {+ "type": "string"+ },++ "planPrice": {+ "type": "number"+ },++ "stripeProductId": {+ "type": "string"+ },++ "stripePriceId": {+ "type": "string"+ },++ "planLimits": {+ "type": "object",+ "schema": {+ "properties": {+ "prodAiAgents": {+ "type": "number"+ },+ "devAiAgents": {+ "type": "number"+ },+ "teamMembers": {+ "type": "number"+ }+ }+ }+ },++ "featureFlags": {+ "type": "object",+ "schema": {+ "properties": {+ "embodimentsEnabled": {+ "type": "boolean"+ },+ "agentAuthSidebarEnabled": {+ "type": "boolean"+ },+ "domainRegistrationEnabled": {+ "type": "boolean"+ }+ }+ }+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "type": "object",+ "properties": {+ "embodiments": {+ "type": "object"+ }+ }+ }+ }+ }+ },++ "get": {+ "tags": ["Plans"],+ "summary": "Get all plans",+ "description": "Get all plans",+ "operationId": "getPlans",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "page",+ "in": "query",+ "description": "Page number",+ "required": false,+ "type": "integer"+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Number of results per page",+ "required": false,+ "type": "integer"+ }+ ],++ "responses": {+ "200": {+ "description": "plans",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/plans/{id}": {+ "put": {+ "tags": ["Plans"],+ "summary": "Edit a plan",+ "description": "Edit a plan",+ "operationId": "editPlan",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "plan id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing job data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "planName": {+ "type": "string"+ },++ "planPrice": {+ "type": "number"+ },++ "stripeProductId": {+ "type": "string"+ },++ "stripePriceId": {+ "type": "string"+ },++ "planLimits": {+ "type": "object",+ "schema": {+ "properties": {+ "prodAiAgents": {+ "type": "number"+ },+ "devAiAgents": {+ "type": "number"+ },+ "teamMembers": {+ "type": "number"+ }+ }+ }+ },++ "featureFlags": {+ "type": "object",+ "schema": {+ "properties": {+ "embodimentsEnabled": {+ "type": "boolean"+ },+ "agentAuthSidebarEnabled": {+ "type": "boolean"+ },+ "domainRegistrationEnabled": {+ "type": "boolean"+ }+ }+ }+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "type": "object",+ "properties": {+ "embodiments": {+ "type": "object"+ }+ }+ }+ }+ }+ }+ },++ "/app-config/settings": {+ "get": {+ "tags": ["App Config"],+ "summary": "Get all settings",+ "description": "Get all settings",+ "operationId": "getSettings",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "responses": {+ "200": {+ "description": "settings",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "put": {+ "tags": ["App Config"],+ "summary": "Create a setting",+ "description": "Create a setting",+ "operationId": "createSetting",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing setting data",+ "required": true,+ "schema": {+ "properties": {+ "key": {+ "type": "string"+ },+ "value": {+ "type": "string"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "setting",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/app-config/settings/{key}": {+ "get": {+ "tags": ["App Config"],+ "summary": "Get a setting",+ "description": "Get a setting",+ "operationId": "getSetting",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "key",+ "in": "path",+ "description": "Setting key",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "setting",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "delete": {+ "tags": ["App Config"],+ "summary": "Delete a setting",+ "description": "Delete a setting",+ "operationId": "deleteSetting",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "key",+ "in": "path",+ "description": "Setting key",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "setting",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/app-config/components": {+ "get": {+ "tags": ["App Config"],+ "summary": "Get all components",+ "description": "Get all components",+ "operationId": "getComponents",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "responses": {+ "200": {+ "description": "components",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "post": {+ "tags": ["App Config"],+ "summary": "Create a component",+ "description": "Create a component",+ "operationId": "createComponent",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing component data",+ "required": true,+ "schema": {+ "properties": {+ "name": {+ "type": "string"+ },+ "data": {+ "type": "string"+ },+ "collectionId": {+ "type": "string"+ },++ "order": {+ "type": "number"+ },+ "visible": {+ "type": "boolean"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "component",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/app-config/components/{componentId}": {+ "get": {+ "tags": ["App Config"],+ "summary": "Get a component",+ "description": "Get a component",+ "operationId": "getComponent",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "componentId",+ "in": "path",+ "description": "Component id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "component",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "put": {+ "tags": ["App Config"],+ "summary": "Update a component",+ "description": "Update a component",+ "operationId": "updateComponent",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "componentId",+ "in": "path",+ "description": "Component id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing component data",+ "required": true,+ "schema": {+ "properties": {+ "name": {+ "type": "string"+ },+ "data": {+ "type": "string"+ },+ "collectionId": {+ "type": "string"+ },+ "order": {+ "type": "number"+ },+ "visible": {+ "type": "boolean"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "component",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "delete": {+ "tags": ["App Config"],+ "summary": "Delete a component",+ "description": "Delete a component",+ "operationId": "deleteComponent",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "componentId",+ "in": "path",+ "description": "Component id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "component",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/app-config/collections": {+ "get": {+ "tags": ["App Config"],+ "summary": "Get all collections",+ "description": "Get all collections",+ "operationId": "getCollections",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "responses": {+ "200": {+ "description": "collections",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "post": {+ "tags": ["App Config"],+ "summary": "Create a collection",+ "description": "Create a collection",+ "operationId": "createCollection",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing collection data",+ "required": true,+ "schema": {+ "properties": {+ "name": {+ "type": "string"+ },+ "icon": {+ "type": "string"+ },+ "order": {+ "type": "number"+ },+ "visible": {+ "type": "boolean"+ },+ "color": {+ "type": "string"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "collection",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/app-config/collections/{collectionId}": {+ "get": {+ "tags": ["App Config"],+ "summary": "Get a collection",+ "description": "Get a collection",+ "operationId": "getCollection",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "collectionId",+ "in": "path",+ "description": "Collection id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "collection",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "put": {+ "tags": ["App Config"],+ "summary": "Update a collection",+ "description": "Update a collection",+ "operationId": "updateCollection",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "collectionId",+ "in": "path",+ "description": "Collection id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing collection data",+ "required": true,+ "schema": {+ "properties": {+ "name": {+ "type": "string"+ },+ "icon": {+ "type": "string"+ },+ "order": {+ "type": "number"+ },+ "visible": {+ "type": "boolean"+ },+ "color": {+ "type": "string"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "collection",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "delete": {+ "tags": ["App Config"],+ "summary": "Delete a collection",+ "description": "Delete a collection",+ "operationId": "deleteCollection",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "collectionId",+ "in": "path",+ "description": "Collection id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "collection",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/app-config/collections/{collectionId}/components": {+ "get": {+ "tags": ["App Config"],+ "summary": "Get all components in a collection",+ "description": "Get all components in a collection",+ "operationId": "getCollectionComponents",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "collectionId",+ "in": "path",+ "description": "Collection id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "components",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/user/{userId}/settings": {+ "get": {+ "tags": ["User"],+ "summary": "Get settings",+ "description": "Get settings",+ "operationId": "getSettings",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "userId",+ "in": "path",+ "description": "User id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "put": {+ "tags": ["User"],+ "summary": "Create/Update settings",+ "description": "Update settings",+ "operationId": "updateSettings",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "userId",+ "in": "path",+ "description": "User id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing settings data",+ "required": true,+ "schema": {+ "$ref": "#/definitions/SettingsRequest"+ }+ }+ ],+ "security": [+ {+ "Bearer": []+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/user/{userId}/settings/{settingKey}": {+ "delete": {+ "tags": ["User"],+ "security": [+ {+ "Bearer": []+ }+ ],++ "summary": "Delete setting",+ "description": "Delete setting",+ "operationId": "deleteSetting",+ "produces": ["application/json"],++ "parameters": [+ {+ "name": "userId",+ "in": "path",+ "description": "User id",+ "required": true,+ "type": "string"+ },+ {+ "name": "settingKey",+ "in": "path",+ "description": "Setting key",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "get": {+ "tags": ["User"],+ "summary": "Get setting",+ "description": "Get setting",+ "operationId": "getSetting",+ "security": [+ {+ "Bearer": []+ }+ ],++ "parameters": [+ {+ "name": "userId",+ "in": "path",+ "description": "User id",+ "required": true,+ "type": "string"+ },+ {+ "name": "settingKey",+ "in": "path",+ "description": "Setting key",+ "required": true,+ "type": "string"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ }+ },++ "definitions": {+ "GenericErrorModel": {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer"+ },+ "message": {+ "type": "string"+ }+ },+ "required": ["errors"]+ },+ "Domain": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ }+ }+ },+ "Endpoint": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string"+ },+ "method": {+ "type": "string"+ },+ "domainName": {+ "type": "string"+ }+ }+ },+ "SettingsRequest": {+ "type": "object",+ "properties": {+ "settingKey": {+ "type": "string"+ },+ "settingValue": {+ "type": "string"+ }+ }+ },+ "AgentSettingsRequest": {+ "type": "object",+ "properties": {+ "key": {+ "type": "string"+ },+ "value": {+ "type": "string"+ }+ }+ },+ "DomainEndpointData": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string"+ },+ "data": {+ "type": "object",+ "properties": {+ "method": {+ "type": "string",+ "enum": ["GET", "POST", "PUT", "DELETE"]+ },+ "componentId": {+ "type": "string"+ }+ }+ },+ "agentId": {+ "type": "string"+ },+ "domainName": {+ "type": "string"+ }+ }+ },+ "ResponseMessage": {+ "type": "object",+ "properties": {+ "message": {+ "type": "string"+ }+ }+ },++ "DatasourceType": {+ "type": "string",+ "enum": ["PDF", "WORD", "SITEMAP", "WEBPAGE"]+ },++ "Agent": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "status": {+ "type": "string"+ },+ "createdAt": {+ "type": "string"+ },+ "updatedAt": {+ "type": "string"+ }+ }+ },++ "AgentRequest": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "data": {+ "type": "object"+ }+ }+ }+ }+}diff --git a/packages/middleware/docs/swagger.json b/packages/middleware/docs/swagger.jsonnew file mode 100644index 00000000..cda5e025--- /dev/null+++ b/packages/middleware/docs/swagger.json@@ -0,0 +1,5217 @@+{+ "swagger": "2.0",+ "info": {+ "description": "Smyth API",+ "version": "1.0.0",+ "title": "Smyth API",+ "basePath": "/v1",+ "license": {+ "name": "MIT License",+ "url": "https://opensource.org/licenses/MIT"+ }+ },+ "basePath": "/v1",+ "schemes": ["http", "https"],+ "produces": ["application/json"],+ "consumes": ["application/json"],+ "securityDefinitions": {+ "Bearer": {+ "description": "For accessing the protected API resources, you must have received a valid token after registering or logging in. This JWT token must then be used for all protected resources by passing it in via the 'Authorization' header.\n\nA JWT token is generated by the API by either registering via /users or logging in via /users/login. The following format must be in the 'Authorization' header :\n\n Token: xxxxxx.yyyyyyy.zzzzzz\n",+ "type": "apiKey",+ "name": "Authorization",+ "in": "header"+ },+ "TeamId": {+ "description": "For accessing the protected API resources, you must have received a valid token after registering or logging in. This JWT token must then be used for all protected resources by passing it in via the 'Authorization' header.\n\nA JWT token is generated by the API by either registering via /users or logging in via /users/login. The following format must be in the 'Authorization' header :\n\n Token: xxxxxx.yyyyyyy.zzzzzz\n",+ "type": "apiKey",+ "name": "x-smyth-team-id",+ "in": "header"+ }+ },+ "definitions": {+ "GenericErrorModel": {+ "type": "object",+ "properties": {+ "code": {+ "type": "integer"+ },+ "message": {+ "type": "string"+ }+ },+ "required": ["errors"]+ },+ "Domain": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ }+ }+ },+ "Endpoint": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string"+ },+ "method": {+ "type": "string"+ },+ "domainName": {+ "type": "string"+ }+ }+ },+ "SettingsRequest": {+ "type": "object",+ "properties": {+ "settingKey": {+ "type": "string"+ },+ "settingValue": {+ "type": "string"+ }+ }+ },+ "AgentSettingsRequest": {+ "type": "object",+ "properties": {+ "key": {+ "type": "string"+ },+ "value": {+ "type": "string"+ }+ }+ },+ "DomainEndpointData": {+ "type": "object",+ "properties": {+ "path": {+ "type": "string"+ },+ "data": {+ "type": "object",+ "properties": {+ "method": {+ "type": "string",+ "enum": ["GET", "POST", "PUT", "DELETE"]+ },+ "componentId": {+ "type": "string"+ }+ }+ },+ "agentId": {+ "type": "string"+ },+ "domainName": {+ "type": "string"+ }+ }+ },+ "ResponseMessage": {+ "type": "object",+ "properties": {+ "message": {+ "type": "string"+ }+ }+ },+ "ResponseMessageWithData": {+ "type": "object",+ "properties": {+ "message": {+ "type": "string"+ },+ "data": {+ "type": "object"+ }+ }+ },++ "DatasourceType": {+ "type": "string",+ "enum": ["PDF", "WORD", "SITEMAP", "WEBPAGE"]+ },++ "Agent": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "status": {+ "type": "string"+ },+ "createdAt": {+ "type": "string"+ },+ "updatedAt": {+ "type": "string"+ }+ }+ },++ "AgentRequest": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "description": {+ "type": "string"+ },+ "data": {+ "type": "object"+ }+ }+ },+ "VaultSecretRequest": {+ "type": "object",+ "properties": {+ "teamId": {+ "type": "string",+ "description": "Team ID"+ },+ "secretId": {+ "type": "string",+ "description": "Secret ID"+ },+ "key": {+ "type": "string",+ "description": "Secret key",+ "maxLength": 300+ },+ "value": {+ "type": "string",+ "description": "Secret value",+ "maxLength": 10000+ },+ "metadata": {+ "type": "object",+ "description": "Optional metadata"+ }+ },+ "required": ["teamId", "secretId", "key", "value"]+ },+ "VaultSecretMetadataRequest": {+ "type": "object",+ "properties": {+ "metadata": {+ "type": "object",+ "description": "Secret metadata"+ }+ },+ "required": ["metadata"]+ }+ },++ "paths": {+ "/user/me": {+ "get": {+ "tags": ["User"],+ "summary": "Get my user",+ "description": "Get my user",+ "operationId": "getMyUser",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "my user",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/user/account": {+ "delete": {+ "tags": ["User"],+ "summary": "Delete user account",+ "description": "Delete user account",+ "operationId": "deleteUserAccount",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "deleted user account",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/user/settings": {+ "get": {+ "tags": ["User"],+ "summary": "Get settings",+ "description": "Get settings",+ "operationId": "getSettings",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "put": {+ "tags": ["User"],+ "summary": "Create/Update settings",+ "description": "Update settings",+ "operationId": "updateSettings",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing settings data",+ "required": true,+ "schema": {+ "$ref": "#/definitions/SettingsRequest"+ }+ }+ ],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/user/settings/{settingKey}": {+ "delete": {+ "tags": ["User"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "summary": "Delete setting",+ "description": "Delete setting",+ "operationId": "deleteSetting",+ "produces": ["application/json"],++ "parameters": [+ {+ "name": "settingKey",+ "in": "path",+ "description": "Setting key",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "get": {+ "tags": ["User"],+ "summary": "Get setting",+ "description": "Get setting",+ "operationId": "getSetting",+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "settingKey",+ "in": "path",+ "description": "Setting key",+ "required": true,+ "type": "string"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/me": {+ "get": {+ "tags": ["Teams"],+ "summary": "Get my team",+ "description": "Get my team",+ "operationId": "getMyTeam",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "my team",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/{teamId}/name": {+ "put": {+ "tags": ["Teams"],+ "summary": "Update team name",+ "description": "Update team name",+ "operationId": "updateTeamName",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing team name",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "updated team name",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/me/leave": {+ "post": {+ "tags": ["Teams"],+ "summary": "Leave team",+ "description": "Leave team",+ "operationId": "leaveTeam",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "left team",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/members": {+ "get": {+ "tags": ["Teams"],+ "summary": "List all team members",+ "description": "List team members",+ "operationId": "getTeamMembers",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "includeRoles",+ "in": "query",+ "description": "Include roles",+ "required": false,+ "type": "boolean"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/members/{memberId}/role": {+ "put": {+ "tags": ["Teams"],+ "summary": "Update team member role",+ "description": "Update team member role",+ "operationId": "updateTeamMemberRole",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "memberId",+ "in": "path",+ "description": "Member id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Role data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "roleId": {+ "type": "number"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "updated team member role",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/members/{memberId}": {+ "delete": {+ "tags": ["Teams"],+ "summary": "Delete team member",+ "description": "Delete team member",+ "operationId": "deleteTeamMember",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "memberId",+ "in": "path",+ "description": "Member id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "deleted team member",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/subteams": {+ "post": {+ "tags": ["Teams"],+ "summary": "Create subteam",+ "description": "Create subteam",+ "operationId": "createSubteam",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Subteam data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "created subteam",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/teams/subteams/{subteamId}": {+ "delete": {+ "tags": ["Teams"],+ "summary": "Delete subteam",+ "description": "Delete subteam",+ "operationId": "deleteSubteam",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "subteamId",+ "in": "path",+ "description": "Subteam id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "deleted subteam",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/{subteamId}/members/assign/{memberId}": {+ "put": {+ "tags": ["Teams"],+ "summary": "Assign team member to a sub-team (works for sub-teams only)",+ "description": "Assign team member",+ "operationId": "assignTeamMember",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "subteamId",+ "in": "path",+ "description": "Subteam id",+ "required": true,+ "type": "string"+ },+ {+ "name": "memberId",+ "in": "path",+ "description": "Member id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Role data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "roleId": {+ "type": "number"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "assigned team member",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/{subteamId}/members/unassign/{memberId}": {+ "delete": {+ "tags": ["Teams"],+ "summary": "Unassign team member from a sub-team (works for sub-teams only)",+ "description": "Unassign team member",+ "operationId": "unassignTeamMember",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "subteamId",+ "in": "path",+ "description": "Subteam id",+ "required": true,+ "type": "string"+ },+ {+ "name": "memberId",+ "in": "path",+ "description": "Member id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "unassigned team member",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/roles/me": {+ "get": {+ "tags": ["Teams"],+ "summary": "Get my roles",+ "description": "Get my roles",+ "operationId": "getMyRoles",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "my roles",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/roles": {+ "get": {+ "tags": ["Teams"],+ "summary": "List all Team roles",+ "description": "List roles",+ "operationId": "getRoles",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "roles",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "post": {+ "tags": ["Teams"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "summary": "Add Team role",+ "description": "Add Team role that can be assigned to team members",+ "operationId": "addRole",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Role data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "canManageTeam": {+ "type": "boolean"+ },+ "acl": {+ "type": "object"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "added role",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "put": {+ "tags": ["Teams"],+ "summary": "Update Team role",+ "description": "Update Team role",+ "operationId": "updateRole",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Role data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "roleId": {+ "type": "number"+ },+ "canManageTeam": {+ "type": "boolean"+ },+ "acl": {+ "type": "object"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "updated role",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/roles/{roleId}": {+ "delete": {+ "tags": ["Teams"],+ "summary": "Delete Team role",+ "description": "Delete role",+ "operationId": "deleteRole",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "roleId",+ "in": "path",+ "description": "Role id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "deleted role",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "get": {+ "tags": ["Teams"],+ "summary": "Get role",+ "description": "Get role",+ "operationId": "getRole",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "roleId",+ "in": "path",+ "description": "Role id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "role",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/invitations": {+ "post": {+ "tags": ["Teams"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "summary": "Invite team member",+ "description": "Invite team member",+ "operationId": "inviteTeamMember",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Invite data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "email": {+ "type": "string"+ },+ "roleId": {+ "type": "number"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "invited team member",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "get": {+ "tags": ["Teams"],+ "summary": "List all team invitations",+ "description": "List team invitations",+ "operationId": "getTeamInvitations",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "team invitations",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/invitations/{invitationId}/accept": {+ "post": {+ "tags": ["Teams"],+ "summary": "Accept team invitation",+ "description": "Accept team invitation",+ "operationId": "acceptTeamInvitation",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "invitationId",+ "in": "path",+ "description": "Invitation id",+ "required": true,+ "type": "string"+ }+ ],++ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "responses": {+ "200": {+ "description": "accepted team invitation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/teams/settings": {+ "get": {+ "tags": ["Teams"],+ "summary": "Get team settings",+ "description": "Get team settings",+ "operationId": "getTeamSettings",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "put": {+ "tags": ["Teams"],+ "summary": "Create/Update team settings",+ "description": "Update team settings",+ "operationId": "updateTeamSettings",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing settings data",+ "required": true,+ "schema": {+ "$ref": "#/definitions/SettingsRequest"+ }+ }+ ],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/teams/settings/{settingKey}": {+ "delete": {+ "tags": ["Teams"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "summary": "Delete team setting",+ "description": "Delete team setting",+ "operationId": "deleteTeamSetting",+ "produces": ["application/json"],++ "parameters": [+ {+ "name": "settingKey",+ "in": "path",+ "description": "Setting key",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "get": {+ "tags": ["Teams"],+ "summary": "Get setting",+ "description": "Get setting",+ "operationId": "getTeamSetting",+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "settingKey",+ "in": "path",+ "description": "Setting key",+ "required": true,+ "type": "string"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/subscriptions/me": {+ "get": {+ "tags": ["Subscriptions"],+ "summary": "Get my team subscription",+ "description": "Get my team subscription",+ "operationId": "getMyTeamSubscription",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "includeObject",+ "in": "query",+ "description": "Include expanded subs object",+ "required": false,+ "type": "boolean"+ }+ ],++ "responses": {+ "200": {+ "description": "my subscription",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/subscriptions/checkout/generate-session": {+ "post": {+ "tags": ["Subscriptions"],+ "summary": "Generate subscription session",+ "description": "Generate subscription session",+ "operationId": "generateSubscriptionSession",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing subscription data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "priceId": {+ "type": "string"+ },+ "susccessUrl": {+ "type": "string"+ },+ "returnUrl": {+ "type": "string"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "subscription session",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/subscriptions/change-plan": {+ "post": {+ "tags": ["Subscriptions"],+ "summary": "Upgrade/downgrade subscription",+ "description": "Upgrade/downgrade subscription",+ "operationId": "changeSubscription",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing subscription data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "newPriceId": {+ "type": "string"+ },+ "isUserAcknowledged": {+ "type": "boolean"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "subscription session",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/subscriptions/billing-portal/generate-session": {+ "post": {+ "tags": ["Subscriptions"],+ "summary": "Generate billing session",+ "description": "Generate billing session",+ "operationId": "generateBillingSession",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing subscription data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "returnUrl": {+ "type": "string"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "subscription session",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/subscriptions/v2/checkout/generate-session": {+ "post": {+ "tags": ["Subscriptions V2"],+ "summary": "Generate subscription session",+ "description": "Generate subscription session",+ "operationId": "generateSubscriptionSession",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing subscription data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "priceIds": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "priceId": {+ "type": "string"+ },+ "for": {+ "type": "string",+ "enum": ["tasks usage", "user seats"]+ }+ },+ "required": ["priceId", "for"]+ }+ },+ "successUrl": {+ "type": "string"+ },+ "cancelUrl": {+ "type": "string"+ }+ },+ "required": ["priceIds"]+ }+ }+ ],++ "responses": {+ "200": {+ "description": "subscription session",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/subscriptions/v2/change-plan": {+ "post": {+ "tags": ["Subscriptions V2"],+ "summary": "Upgrade/downgrade subscription",+ "description": "Upgrade/downgrade subscription",+ "operationId": "changeSubscription",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing subscription data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "newPriceIds": {+ "type": "array",+ "description": "Array of price IDs for updating both user seats and task usage.",+ "items": {+ "type": "object",+ "properties": {+ "priceId": {+ "type": "string",+ "description": "The Stripe price ID for user seats or tasks usage."+ },+ "for": {+ "type": "string",+ "enum": ["user seats", "tasks usage"],+ "description": "Indicates whether the price ID is for user seats or task usage."+ }+ },+ "required": ["priceId", "for"]+ }+ },+ "isUserAcknowledged": {+ "type": "boolean"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "subscription session",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/subscriptions/validate-promo-code": {+ "post": {+ "tags": ["Subscriptions V2"],+ "summary": "Validate promo code",+ "description": "Validate promo code",+ "operationId": "validatePromoCode",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Promo code",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "promoCode": {+ "type": "string"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "valid: boolean, promoCode: any",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/quota/usage": {+ "get": {+ "tags": ["Quota"],+ "summary": "Get team subs quota usage",+ "description": "Get team subs quota",+ "operationId": "getTeamSubsQuotaUsage",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "task quota",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/quota/usage/features": {+ "get": {+ "tags": ["Quota"],+ "summary": "Get team features quota usage",+ "description": "Get team features quota",+ "operationId": "getTeamFeaturesQuotaUsage",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "features quota",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/quota/current-cycle/usage": {+ "get": {+ "tags": ["Quota"],+ "summary": "Get total usage for current billing cycle for all spaces",+ "description": "Get total usage for current billing cycle",+ "operationId": "getTotalUsageForBillingCycle",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": []+ }+ ],+ "parameters": [],+ "responses": {+ "200": {+ "description": "Total usage for current billing cycle",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agents": {+ "get": {+ "tags": ["Agents"],+ "summary": "Get all agents",+ "description": "Get all agents",+ "operationId": "getAgents",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "includeSettings",+ "in": "query",+ "description": "Include agent settings",+ "required": false,+ "type": "boolean"+ },+ {+ "name": "contributors",+ "in": "query",+ "description": "Include agent contributors",+ "required": false,+ "type": "boolean"+ },+ {+ "name": "agentActivity",+ "in": "query",+ "description": "Include agent activity log",+ "required": false,+ "type": "boolean"+ },+ {+ "name": "page",+ "in": "query",+ "description": "Page number",+ "required": false,+ "type": "integer"+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Number of results per page",+ "required": false,+ "type": "integer"+ },+ {+ "name": "search",+ "in": "query",+ "description": "Search term",+ "required": false,+ "type": "string"+ },+ {+ "name": "sortField",+ "in": "query",+ "description": "Sort by",+ "required": false,+ "type": "string"+ },+ {+ "name": "order",+ "in": "query",+ "description": "Sort order",+ "required": false,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agents/models": {+ "get": {+ "tags": ["Agents"],+ "summary": "Get all model agents",+ "description": "Get all model agents",+ "operationId": "getModelAgents",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/{agentId}": {+ "delete": {+ "tags": ["Agents"],+ "summary": "Delete agent",+ "description": "Delete agent",+ "operationId": "deleteAgent",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "get": {+ "tags": ["Agents"],+ "summary": "Get agent",+ "description": "Get agent",+ "operationId": "getAgent",+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "include",+ "in": "query",+ "description": "extended data",+ "required": false,+ "type": "array"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/ai-agent/{agentId}/lock-status": {+ "get": {+ "tags": ["Agents"],+ "summary": "Get agent lock status",+ "description": "Get agent lock status",+ "operationId": "getAgentLockStatus",+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/ai-agent": {+ "post": {+ "tags": ["Agents"],+ "summary": "Create or Update agent",+ "description": "Create or Update agent",+ "operationId": "postAgent",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing agent data. Include (`id` and `lockId` for updates)",+ "required": true,+ "schema": {+ "$ref": "#/definitions/AgentRequest"+ }+ }+ ],++ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/lock": {+ "put": {+ "tags": ["Agents"],+ "summary": "Request agent lock",+ "description": "Lock agent",+ "operationId": "lockAgent",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing agent deployment data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "agentId": {+ "type": "string"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "locked agent",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/ai-agent/lock/release": {+ "put": {+ "tags": ["Agents"],+ "summary": "Release agent lock",+ "description": "Release agent lock",+ "operationId": "releaseAgentLock",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing agent deployment data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "agentId": {+ "type": "string"+ },+ "lockId": {+ "type": "string"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "released agent lock",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/ai-agent/lock/refresh": {+ "put": {+ "tags": ["Agents"],+ "summary": "Refresh agent lock",+ "description": "Refresh agent lock",+ "operationId": "refreshAgentLock",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing agent deployment data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "agentId": {+ "type": "string"+ },+ "lockId": {+ "type": "string"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "refreshed agent lock",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/chats": {+ "post": {+ "tags": ["Chats"],+ "summary": "Create conversation",+ "description": "Create conversation",+ "operationId": "createConversation",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing conversation data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "conversation": {+ "type": "object",+ "properties": {+ "label": {+ "type": "string",+ "default": ""+ },+ "summary": {+ "type": "string",+ "default": ""+ },++ "aiAgentId": {+ "type": "string"+ },+ "chunkSize": {+ "type": "number",+ "default": null+ },+ "lastChunkID": {+ "type": "string",+ "default": null+ }+ }+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "get": {+ "tags": ["Chats"],+ "summary": "Get all team conversations",+ "description": "Get all team conversations",+ "operationId": "getTeamConversations",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "isOwner",+ "in": "query",+ "description": "Only conversations owned by the user",+ "required": false,+ "type": "boolean"+ },+ {+ "name": "page",+ "in": "query",+ "description": "Page number",+ "required": false,+ "default": 1,+ "type": "number"+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Number of results per page",+ "required": false,+ "default": 10,+ "type": "number"+ },+ {+ "name": "sortField",+ "in": "query",+ "description": "Sort by this field. Possible values: createdAt, updatedAt, label.",+ "required": false,+ "default": "createdAt",+ "type": "string"+ },+ {+ "name": "order",+ "in": "query",+ "description": "Sort order. Possible values: asc, desc.",+ "required": false,+ "default": "desc",+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful operation",+ "schema": {+ "type": "object",+ "properties": {+ "data": {+ "type": "object",+ "properties": {+ "total": {+ "type": "number"+ },+ "conversations": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "summary": {+ "type": "string"+ },+ "aiAgentId": {+ "type": "string"+ },+ "chunkSize": {+ "type": "number"+ },+ "lastChunkID": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+ }+ },++ "/chats/me": {+ "get": {+ "tags": ["Chats"],+ "summary": "Get my conversations",+ "description": "Get my conversations",+ "operationId": "getMyConversations",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "page",+ "in": "query",+ "description": "Page number",+ "required": false,+ "type": "boolean"+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Number of results per page",+ "required": false,+ "type": "boolean"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful operation",+ "schema": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "label": {+ "type": "string"+ },+ "summary": {+ "type": "string"+ },+ "aiAgentId": {+ "type": "string"+ },+ "chunkSize": {+ "type": "number"+ },+ "lastChunkID": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ }+ },++ "/ai-agent/{agentId}/deployments": {+ "get": {+ "tags": ["Agent Deployments"],+ "summary": "Get agent deployments",+ "description": "Get agent deployments",+ "operationId": "getAgentDeployments",+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "include",+ "in": "query",+ "description": "extended data",+ "required": false,+ "type": "array"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "agent deployments",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/ai-agent/{agentId}/deployments/latest": {+ "get": {+ "tags": ["Agent Deployments"],+ "summary": "Get agent latest deployment",+ "description": "Get agent latest deployment",+ "operationId": "getAgentLatestDeployment",+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "agent deployments",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/deployments/{deploymentId}": {+ "get": {+ "tags": ["Agent Deployments"],+ "summary": "Get agent deployment",+ "description": "Get agent deployment",+ "operationId": "getAgentDeployment",+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "deploymentId",+ "in": "path",+ "description": "Deployment id",+ "required": true,+ "type": "string"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "agent deployment",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/deployments": {+ "post": {+ "tags": ["Agent Deployments"],+ "summary": "Create agent deployment",+ "description": "Create agent deployment",+ "operationId": "postAgentDeployment",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing agent deployment data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "version": {+ "type": "string"+ },+ "agentId": {+ "type": "string"+ },++ "releaseNotes": {+ "type": "string"+ },++ "distributionId": {+ "type": "string"+ }+ }+ }+ }+ ],++ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "created agent deployment",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/distributions": {+ "get": {+ "tags": ["Distributions"],+ "summary": "Get all distributions",+ "description": "Get all distributions",+ "operationId": "getDistributions",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "page",+ "in": "query",+ "description": "Page number",+ "required": false,+ "type": "integer"+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Number of results per page",+ "required": false,+ "type": "integer"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "post": {+ "tags": ["Distributions"],+ "summary": "Create distribution",+ "description": "Create distribution",+ "operationId": "createDistribution",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing distribution data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "url": {+ "type": "string"+ }+ }+ }+ }+ ],++ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "created distribution",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/distributions/{id}": {+ "get": {+ "tags": ["Distributions"],+ "summary": "Get distribution by ID",+ "description": "Get distribution by ID",+ "operationId": "getDistributionById",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "Distribution ID",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "Successful operation",+ "schema": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "url": {+ "type": "string"+ }+ }+ }+ }+ }+ },++ "delete": {+ "tags": ["Distributions"],+ "summary": "Delete distribution",+ "description": "Delete distribution",+ "operationId": "deleteDistribution",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "id",+ "in": "path",+ "description": "Distribution ID",+ "required": true,+ "type": "string"+ }+ ],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "responses": {+ "200": {+ "description": "Successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/{agentId}/settings": {+ "get": {+ "tags": ["Agent Settings"],+ "summary": "Get settings",+ "description": "Get settings",+ "operationId": "getAgentSettings",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "put": {+ "tags": ["Agent Settings"],+ "summary": "Create/Update settings",+ "description": "Update settings",+ "operationId": "updateAgentSettings",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing settings data",+ "required": true,+ "schema": {+ "$ref": "#/definitions/AgentSettingsRequest"+ }+ }+ ],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/{agentId}/settings/{key}": {+ "delete": {+ "tags": ["Agent Settings"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "summary": "Delete agent setting",+ "description": "Delete agent setting",+ "operationId": "deleteAgentSetting",+ "produces": ["application/json"],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "key",+ "in": "path",+ "description": "Setting key",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "get": {+ "tags": ["Agent Settings"],+ "summary": "Get Agent setting",+ "description": "Get Agent setting",+ "operationId": "getAgentSetting",+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "key",+ "in": "path",+ "description": "Setting key",+ "required": true,+ "type": "string"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/{agentId}/logs/calls": {+ "get": {+ "tags": ["Agent Logs"],+ "summary": "Get agent call logs",+ "description": "Get agent call logs",+ "operationId": "getAgentCallLogs",+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "page",+ "in": "query",+ "description": "Page number",+ "required": false,+ "type": "integer"+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Number of results per page",+ "required": false,+ "type": "integer"+ },++ {+ "name": "sourceId",+ "in": "query",+ "description": "Source id",+ "required": false,+ "type": "string"+ },+ {+ "name": "componentId",+ "in": "query",+ "description": "Component id",+ "required": false,+ "type": "string"+ },+ {+ "name": "sessionID",+ "in": "query",+ "description": "Session id",+ "required": false,+ "type": "string"+ },+ {+ "name": "inputDateFrom",+ "in": "query",+ "description": "Input date from",+ "required": false,+ "type": "string"+ },+ {+ "name": "inputDateTo",+ "in": "query",+ "description": "Input date to",+ "required": false,+ "type": "string"+ },+ {+ "name": "outputDateFrom",+ "in": "query",+ "description": "Output date from",+ "required": false,+ "type": "string"+ },+ {+ "name": "outputDateTo",+ "in": "query",+ "description": "Output date to",+ "required": false,+ "type": "string"+ },+ {+ "name": "tags",+ "in": "query",+ "description": "Tags",+ "required": false,+ "type": "string"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "agent call logs",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/{agentId}/logs/sessions": {+ "get": {+ "tags": ["Agent Logs"],+ "summary": "Get agent call logs sessions",+ "description": "Get agent call logs sessions",+ "operationId": "getAgentCallLogsGroupedBySession",+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "page",+ "in": "query",+ "description": "Page number",+ "required": false,+ "type": "integer"+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Number of results per page",+ "required": false,+ "type": "integer"+ }+ ],++ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "agent call logs",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/ai-agent/{agentId}/bulk-calls/progress": {+ "get": {+ "tags": ["Agent Bulk Calls"],+ "summary": "Get bulk agent call progress [LEGACY]",+ "description": "Get bulk agent call progress",+ "operationId": "getBulkAgentCallProgress",+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "componentId",+ "in": "query",+ "description": "Component id",+ "required": false,+ "type": "string"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "agent call logs",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/ai-agent/{agentId}/bulk-calls/latest": {+ "get": {+ "tags": ["Agent Bulk Calls"],+ "summary": "Get latest bulk agent call progress",+ "description": "Get latest bulk agent call progress",+ "operationId": "getLatestBulkAgentCallProgress",+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "componentId",+ "in": "query",+ "description": "Component id",+ "required": false,+ "type": "string"+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "agent call logs",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/ai-agent/{agentId}/skill-call": {+ "post": {+ "tags": ["Agent Calls"],+ "summary": "Create agent call",+ "description": "Create agent call",+ "operationId": "postAgentCall",+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },++ {+ "name": "body",+ "in": "body",+ "description": "Object containing agent call data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "payload": {+ "type": "object"+ },+ "componentId": {+ "type": "string"+ },+ "version": {+ "type": "string"+ }+ }+ }+ }+ ],+ "produces": ["application/json"],++ "responses": {+ "200": {+ "description": "agent call logs",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },+ "/domain": {+ "post": {+ "tags": ["Domains"],+ "summary": "Create Domain",+ "description": "Create Domain",+ "operationId": "postDomain",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing domain data",+ "required": true,+ "schema": {+ "$ref": "#/definitions/Domain"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid domain data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ },++ "put": {+ "tags": ["Domains"],+ "summary": "Update Domain",+ "description": "Update Domain",+ "operationId": "updateDomain",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing updated domain data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "data": {+ "type": "object",+ "properties": {+ "aiAgentId": {+ "type": "string"+ }+ }+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid domain data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/domains": {+ "get": {+ "tags": ["Domains"],+ "summary": "Get all domains",+ "description": "Get all domains [M2M allowed]",+ "operationId": "getDomains",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "verified",+ "in": "query",+ "description": "Domain Status",+ "required": true,+ "type": "boolean"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid request",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/domain/query": {+ "post": {+ "tags": ["Domains"],+ "summary": "Query Domain by name",+ "description": "Query Domain by name [M2M allowed]",+ "operationId": "queryDomain",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing domain data",+ "required": true,+ "schema": {+ "$ref": "#/definitions/Domain"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid domain data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ },+ "404": {+ "description": "Domain not found",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/domain/delete": {+ "post": {+ "tags": ["Domains"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "summary": "Delete Domain",+ "description": "Delete Domain",+ "operationId": "deleteDomain",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing domain data",+ "required": true,+ "schema": {+ "$ref": "#/definitions/Domain"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid domain data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ },+ "404": {+ "description": "Domain not found",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/domain/{name}/verify": {+ "get": {+ "description": "Check if domain is verified",+ "operationId": "verifyDomain",+ "parameters": [+ {+ "name": "name",+ "in": "path",+ "description": "Domain name",+ "required": true,+ "type": "string"+ }+ ],+ "produces": ["application/json"],+ "responses": {+ "200": {+ "description": "Domain verified",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "404": {+ "description": "Domain not found",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ },+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "tags": ["Domains"],+ "summary": "Check Verification status of a Domain"+ }+ },+ "/domain/{name}/get-cname-target": {+ "get": {+ "description": "Get domain CNAME target host",+ "summary": "Get CNAME target host of a Domain",+ "operationId": "getCnameTarget",+ "parameters": [+ {+ "name": "name",+ "in": "path",+ "description": "Domain name",+ "required": true,+ "type": "string"+ }+ ],+ "produces": ["application/json"],+ "responses": {+ "200": {+ "description": "CNAME target host",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ },+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "tags": ["Domains"]+ }+ },++ "/domain/{name}/status": {+ "get": {+ "description": "Get domain status",+ "operationId": "getDomainStatus",+ "parameters": [+ {+ "name": "name",+ "in": "path",+ "description": "Domain name",+ "required": true,+ "type": "string"+ }+ ],+ "produces": ["application/json"],+ "responses": {+ "200": {+ "description": "Domain status",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "404": {+ "description": "Domain not found",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ },+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "tags": ["Domains"],+ "summary": "Get Domain status"+ }+ },++ "/domain/endpoint/query": {+ "post": {+ "tags": ["Endpoints"],+ "summary": "Query Endpoint by path, domain name and method",+ "description": "Query Endpoint by path, domain name and method",+ "operationId": "queryEndpoint",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing endpoint data",+ "required": true,+ "schema": {+ "$ref": "#/definitions/Endpoint"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid endpoint data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ },+ "404": {+ "description": "Endpoint not found",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/domain/endpoint": {+ "post": {+ "tags": ["Endpoints"],+ "summary": "Create or update endpoint",+ "description": "Create or update endpoint",+ "operationId": "postEndpoint",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing endpoint data",+ "required": true,+ "schema": {+ "$ref": "#/definitions/DomainEndpointData"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid endpoint data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/domain/endpoint/delete": {+ "post": {+ "tags": ["Endpoints"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "summary": "Delete Endpoint",+ "description": "Delete Endpoint",+ "operationId": "deleteEndpoint",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing endpoint data",+ "required": true,+ "schema": {+ "$ref": "#/definitions/Endpoint"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid endpoint data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ },+ "404": {+ "description": "Endpoint not found",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/vectors/namespaces": {+ "get": {+ "tags": ["Vectors"],+ "summary": "Get all vector namespaces",+ "description": "Get all vector namespaces",+ "operationId": "getVectorNamespaces",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "page",+ "in": "query",+ "description": "Page number",+ "required": false,+ "type": "integer"+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Number of results per page",+ "required": false,+ "type": "integer"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "post": {+ "tags": ["Vectors"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "summary": "Add vector namespace",+ "description": "Add vector namespace",+ "operationId": "addNamespace",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing endpoint data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "useCustomVectorStorage": {+ "type": "boolean"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid request data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/vectors/namespaces/{namespaceName}": {+ "delete": {+ "tags": ["Vectors"],+ "parameters": [+ {+ "name": "namespaceName",+ "in": "path",+ "description": "Namespace name",+ "required": true,+ "type": "string"+ }+ ],+ "summary": "Delete vector namespace",+ "description": "Delete namespace",+ "operationId": "deleteNamespace",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "deleted namespace",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vectors/namespaces/search": {+ "get": {+ "tags": ["Vectors"],+ "summary": "Query Namespace",+ "description": "Run similarity search on a namespace. For M2M calls, pass the 'namespaceId' instead of 'namespaceName' in the query params",+ "operationId": "runSimilaritySearch",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "query",+ "in": "query",+ "description": "Query",+ "required": true,+ "type": "string"+ },+ {+ "name": "raw",+ "in": "query",+ "description": "Include metadata",+ "required": false,+ "type": "boolean"+ },+ {+ "name": "topK",+ "in": "query",+ "description": "Number of results",+ "required": true,+ "type": "integer"+ },+ {+ "name": "namespaceName",+ "in": "query",+ "description": "Namespace name",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vectors/datasources": {+ "get": {+ "tags": ["Vectors"],+ "summary": "List all datasources",+ "description": "List datasources",+ "operationId": "getDatasources",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "namespaceName",+ "in": "query",+ "description": "Namespace name",+ "required": true,+ "type": "string"+ },+ {+ "name": "page",+ "in": "query",+ "description": "Page number",+ "required": false,+ "type": "integer"+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Number of results per page",+ "required": false,+ "type": "integer"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "post": {+ "tags": ["Vectors"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "summary": "Add datasource",+ "description": "Add vector datasource",+ "operationId": "addDatasource",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Datasource data. for 'type' field, please refer to 'DatasourceType' model at the bottom of the page",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "type": {+ "type": "string",+ "enum": ["SITEMAP", "PDF", "WORD", "WEBPAGE"]+ },+ "name": {+ "type": "string"+ },+ "url": {+ "type": "string"+ },+ "namespaceName": {+ "type": "string"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid request data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/vectors/datasources/text": {+ "post": {+ "tags": ["Vectors"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "summary": "Add datasource text",+ "description": "Add vector datasource text",+ "operationId": "addDatasourceText",+ "produces": ["application/json"],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Datasource data. for 'type' field, please refer to 'DatasourceType' model at the bottom of the page",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "text": {+ "type": "string"+ },+ "namespaceId": {+ "type": "string"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid request data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/vectors/datasources/{dataSourceId}": {+ "get": {+ "tags": ["Vectors"],+ "summary": "Get datasource details",+ "description": "Get datasource details",+ "operationId": "getDatasource",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "dataSourceId",+ "in": "path",+ "description": "Datasource id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },++ "delete": {+ "tags": ["Vectors"],+ "summary": "Delete datasource",+ "description": "Delete datasource",+ "operationId": "deleteDatasource",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "dataSourceId",+ "in": "path",+ "description": "Datasource id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "deleted datasource",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vectors/datasources/{dataSourceId}/status": {+ "get": {+ "tags": ["Vectors"],+ "summary": "Check datasource status",+ "description": "Check datasource status",+ "operationId": "getDatasourceStatus",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "dataSourceId",+ "in": "path",+ "description": "Datasource id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vectors/datasources/{dataSourceId}/sitemap_status": {+ "get": {+ "tags": ["Vectors"],+ "summary": "Check datasource SITEMAP status",+ "description": "fetch all urls status from sitemap",+ "operationId": "getSitemapStatus",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "dataSourceId",+ "in": "path",+ "description": "Datasource id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vectors/custom_storage": {+ "get": {+ "tags": ["Vectors"],+ "summary": "Get the team custom vector storage",+ "description": "Get the team custom vector storage",+ "operationId": "getCustomVectprStorage",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "custom storage",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "post": {+ "tags": ["Vectors"],+ "summary": "Add custom vector storage",+ "description": "Add custom vector storage",+ "operationId": "addCustomVectorStorage",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing custom vector storage data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "projectUrl": {+ "type": "string"+ },+ "apiKey": {+ "type": "string"+ },+ "indexName": {+ "type": "string"+ },+ "environment": {+ "type": "string"+ }+ }+ }+ }+ ],++ "responses": {+ "200": {+ "description": "custom storage",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "delete": {+ "tags": ["Vectors"],+ "summary": "Delete custom vector storage",+ "description": "Delete custom vector storage",+ "operationId": "deleteCustomVectorStorage",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "responses": {+ "200": {+ "description": "custom storage",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/embodiments": {+ "post": {+ "tags": ["Embodiments"],+ "summary": "Create embodiment",+ "description": "Create embodiment",+ "operationId": "postEmbodiment",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Embodiment data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "type": {+ "type": "string"+ },+ "properties": {+ "type": "object"+ },+ "aiAgentId": {+ "type": "string"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "type": "object",+ "properties": {+ "embodiments": {+ "type": "object"+ }+ }+ }+ },+ "400": {+ "description": "Invalid request data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ },++ "get": {+ "tags": ["Embodiments"],+ "summary": "Get all embodiments by agent id",+ "description": "Get all embodiments by agent id",+ "operationId": "getEmbodiments",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "aiAgentId",+ "in": "query",+ "description": "Agent Id",+ "required": true,+ "type": "string"+ }+ ],++ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "type": "object",+ "properties": {+ "embodiments": {+ "type": "object"+ }+ }+ }+ }+ }+ },++ "put": {+ "tags": ["Embodiments"],+ "summary": "Update embodiment",+ "description": "Update embodiment",+ "operationId": "updateEmbodiment",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Embodiment data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "type": {+ "type": "string"+ },+ "properties": {+ "type": "object"+ },+ "embodimentId": {+ "type": "number"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "updated embodiment",+ "schema": {+ "type": "object",+ "properties": {+ "embodiments": {+ "type": "object"+ }+ }+ }+ },+ "400": {+ "description": "Invalid request data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/embodiments/{embodimentId}": {+ "get": {+ "tags": ["Embodiments"],+ "summary": "Get embodiment by id",+ "description": "Get embodiment by id",+ "operationId": "getEmbodimentById",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "embodimentId",+ "in": "path",+ "description": "Embodiment id",+ "required": true,+ "type": "number"+ }+ ],++ "responses": {+ "200": {+ "description": "embodiment",+ "schema": {+ "type": "object",+ "properties": {+ "embodiments": {+ "type": "object"+ }+ }+ }+ }+ }+ },++ "delete": {+ "tags": ["Embodiments"],+ "summary": "Delete embodiment",+ "description": "Delete embodiment",+ "operationId": "deleteEmbodiment",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "embodimentId",+ "in": "path",+ "description": "Embodiment id",+ "required": true,+ "type": "number"+ }+ ],++ "responses": {+ "200": {+ "description": "deleted embodiment",+ "schema": {+ "type": "object",+ "properties": {+ "embodiments": {+ "type": "object"+ }+ }+ }+ }+ }+ }+ },++ "/jobs": {+ "post": {+ "tags": ["Jobs"],+ "summary": "Create a job",+ "description": "Create a job",+ "operationId": "createJob",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing job data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "jobType": {+ "type": "string"+ },+ "name": {+ "type": "string"+ },+ "data": {+ "type": "object"+ },+ "options": {+ "type": "object"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ },++ "examples": {+ "application/json": {+ "jobType": "AGENT_SCHEDULE",+ "name": "Send Message",+ "data": {+ "componentId": "component_1",+ "agentId": "clpc800ik9ti44wpjpitt",++ "body": {+ "foo": "bar"+ }+ },+ "options": {+ "repeat": {+ "patternDetails": {+ "daysOfWeek": [0, 1, 2, 3, 4, 5, 6],+ "repeatEveryUnit": "hour",+ "repeatEvery": 1+ },+ "limit": 10,+ "startDate": "2021-01-01T00:00:00.000Z",+ "endDate": "2021-01-01T00:00:00.000Z"+ }+ }+ }+ }+ },+ "400": {+ "description": "Invalid job data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/jobs/{jobId}": {+ "get": {+ "tags": ["Jobs"],+ "summary": "Get a job by id",+ "description": "Get a job by id",+ "operationId": "getJobById",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "jobId",+ "in": "path",+ "description": "Job id",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid job data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ },+ "put": {+ "tags": ["Jobs"],+ "summary": "Update a job",+ "description": "Update a job",+ "operationId": "updateJob",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing job data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ },+ "data": {+ "type": "object"+ },+ "options": {+ "type": "object"+ }+ }+ }+ },+ {+ "name": "jobId",+ "in": "path",+ "description": "Job id",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid job data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ },+ "delete": {+ "tags": ["Jobs"],+ "summary": "Delete a job",+ "description": "Delete a job",+ "operationId": "deleteJob",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "jobId",+ "in": "path",+ "description": "Job id",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid job data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/jobs/agents/{agentId}": {+ "get": {+ "tags": ["Jobs"],+ "summary": "Get all jobs by agent id",+ "description": "Get all jobs by agent id",+ "operationId": "getJobsByAgentId",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ },+ {+ "name": "status",+ "in": "query",+ "description": "status of the job",+ "required": false,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid job data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ },++ "delete": {+ "tags": ["Jobs"],+ "summary": "Delete all jobs by agent id",+ "description": "Delete all jobs by agent id",+ "operationId": "deleteJobsByAgentId",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "agentId",+ "in": "path",+ "description": "Agent id",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid job data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/jobs/components/{componentId}": {+ "delete": {+ "tags": ["Jobs"],+ "summary": "delete a job by component id",+ "description": "delete a job by component id",+ "operationId": "deletJobByComponentId",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "componentId",+ "in": "path",+ "description": "Component id",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid job data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/space": {+ "post": {+ "tags": ["Space"],+ "summary": "Create a space",+ "description": "Create a space",+ "operationId": "createSpace",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Object containing new space data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid space data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/space/list": {+ "get": {+ "tags": ["Space"],+ "summary": "Get all spaces in a team",+ "description": "Get all spaces in the org/team the current user belongs to.",+ "operationId": "getSpaces",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "onlymine",+ "in": "query",+ "description": "Get only spaces created by the current user",+ "required": false,+ "type": "boolean"+ },+ {+ "name": "page",+ "in": "query",+ "description": "Page number",+ "required": false,+ "type": "integer"+ },+ {+ "name": "limit",+ "in": "query",+ "description": "Number of results per page",+ "required": false,+ "type": "integer"+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessageWithData"+ }+ }+ }+ }+ },+ "/space/{spaceId}": {+ "put": {+ "tags": ["Space"],+ "summary": "Update a space",+ "description": "Update a space",+ "operationId": "updateSpace",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "spaceId",+ "in": "path",+ "description": "Space id",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Object containing updated space data",+ "required": true,+ "schema": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string"+ }+ }+ }+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid space data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ },+ "delete": {+ "tags": ["Space"],+ "summary": "Delete a space",+ "description": "Delete a space",+ "operationId": "deleteSpace",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],++ "parameters": [+ {+ "name": "spaceId",+ "in": "path",+ "description": "Space id",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid space data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/space/membership": {+ "get": {+ "tags": ["Space"],+ "summary": "Get all the spaces current user is a member of",+ "description": "Get all the spaces current user is a member of",+ "operationId": "getSpaceMemberships",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessageWithData"+ }+ },+ "400": {+ "description": "Invalid space data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/space/{spaceId}/members": {+ "get": {+ "tags": ["Space"],+ "summary": "Get all members of a space",+ "description": "Get all members of a space",+ "operationId": "getSpaceMembers",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "spaceId",+ "in": "path",+ "description": "Space id",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessageWithData"+ }+ },+ "400": {+ "description": "Invalid space data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },+ "/space/{spaceId}/agents": {+ "get": {+ "tags": ["Space"],+ "summary": "Get all agents of a space",+ "description": "Get all agents of a space",+ "operationId": "getSpaceAgents",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "spaceId",+ "in": "path",+ "description": "Space id",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "successful operation",+ "schema": {+ "$ref": "#/definitions/ResponseMessageWithData"+ }+ },+ "400": {+ "description": "Invalid space data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/vault/v1/api/secret": {+ "post": {+ "tags": ["Vault"],+ "summary": "Create vault secret",+ "description": "Create a new vault secret",+ "operationId": "createVaultSecret",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "body",+ "in": "body",+ "description": "Vault secret data",+ "required": true,+ "schema": {+ "$ref": "#/definitions/VaultSecretRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Secret created successfully",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid request data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ },++ "/vault/v1/api/{teamId}/secrets": {+ "get": {+ "tags": ["Vault"],+ "summary": "Get all secrets for a team",+ "description": "Retrieve all vault secrets for a specific team",+ "operationId": "getAllSecrets",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team ID",+ "required": true,+ "type": "string"+ },+ {+ "name": "metadataFilter",+ "in": "query",+ "description": "Filter secrets by metadata",+ "required": false,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "Secrets retrieved successfully",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vault/v1/api/{teamId}/count/secrets": {+ "get": {+ "tags": ["Vault"],+ "summary": "Get secrets count for a team",+ "description": "Get the total count of secrets for a specific team",+ "operationId": "getSecretsCount",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team ID",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "Secrets count retrieved successfully",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vault/v1/api/{teamId}/secrets/{secretId}": {+ "get": {+ "tags": ["Vault"],+ "summary": "Get secret by ID",+ "description": "Retrieve a specific vault secret by its ID",+ "operationId": "getSecretById",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team ID",+ "required": true,+ "type": "string"+ },+ {+ "name": "secretId",+ "in": "path",+ "description": "Secret ID",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "Secret retrieved successfully",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ },+ "delete": {+ "tags": ["Vault"],+ "summary": "Delete secret by ID",+ "description": "Delete a specific vault secret by its ID",+ "operationId": "deleteSecretById",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team ID",+ "required": true,+ "type": "string"+ },+ {+ "name": "secretId",+ "in": "path",+ "description": "Secret ID",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "Secret deleted successfully",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vault/v1/api/{teamId}/secrets/{secretId}/exists": {+ "get": {+ "tags": ["Vault"],+ "summary": "Check if secret exists by ID",+ "description": "Check if a vault secret exists by its ID",+ "operationId": "checkSecretExistsById",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team ID",+ "required": true,+ "type": "string"+ },+ {+ "name": "secretId",+ "in": "path",+ "description": "Secret ID",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "Secret existence check completed",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vault/v1/api/{teamId}/secrets/name/{secretName}": {+ "get": {+ "tags": ["Vault"],+ "summary": "Get secret by name",+ "description": "Retrieve a vault secret by its name",+ "operationId": "getSecretByName",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team ID",+ "required": true,+ "type": "string"+ },+ {+ "name": "secretName",+ "in": "path",+ "description": "Secret name",+ "required": true,+ "type": "string"+ }+ ],+ "responses": {+ "200": {+ "description": "Secret retrieved successfully",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ }+ }+ }+ },++ "/vault/v1/api/{teamId}/secrets/{secretId}/metadata": {+ "put": {+ "tags": ["Vault"],+ "summary": "Update secret metadata",+ "description": "Update metadata for a specific vault secret",+ "operationId": "updateSecretMetadata",+ "produces": ["application/json"],+ "security": [+ {+ "Bearer": [],+ "TeamId": []+ }+ ],+ "parameters": [+ {+ "name": "teamId",+ "in": "path",+ "description": "Team ID",+ "required": true,+ "type": "string"+ },+ {+ "name": "secretId",+ "in": "path",+ "description": "Secret ID",+ "required": true,+ "type": "string"+ },+ {+ "name": "body",+ "in": "body",+ "description": "Metadata to update",+ "required": true,+ "schema": {+ "$ref": "#/definitions/VaultSecretMetadataRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "Metadata updated successfully",+ "schema": {+ "$ref": "#/definitions/ResponseMessage"+ }+ },+ "400": {+ "description": "Invalid request data",+ "schema": {+ "$ref": "#/definitions/GenericErrorModel"+ }+ }+ }+ }+ }+ }+}diff --git a/packages/middleware/nginx.conf b/packages/middleware/nginx.confnew file mode 100644index 00000000..4d3049f6--- /dev/null+++ b/packages/middleware/nginx.conf@@ -0,0 +1,27 @@+# nginx.conf++events {+ worker_connections 1024;+}++http {+ upstream app_servers {+ # Define each app instance (replace with the container names)+ server app1:3000;+ server app2:3002;+ server app3:3003;+ server app4:3004;+ }++ server {+ listen 80;++ location / {+ proxy_pass http://app_servers;+ proxy_set_header Host $host;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ }+ }+}diff --git a/packages/middleware/nodemon.json b/packages/middleware/nodemon.jsonnew file mode 100644index 00000000..f2d9c6e7--- /dev/null+++ b/packages/middleware/nodemon.json@@ -0,0 +1,6 @@+{+ "watch": ["src", "package.json"],+ "ext": "ts",+ "ignore": ["src/**/*.spec.ts"],+ "exec": "npm run build && node -r esbuild-register dist/index.js"+}diff --git a/packages/middleware/package.json b/packages/middleware/package.jsonnew file mode 100644index 00000000..3e3d3300--- /dev/null+++ b/packages/middleware/package.json@@ -0,0 +1,139 @@+{+ "name": "middleware",+ "version": "1.4.281",+ "description": "",+ "main": "index.js",+ "type": "module",+ "scripts": {+ "test": "vitest --config vitest.config.ts",+ "bump": "pnpm version patch",+ "lint": "eslint --ext .ts src/",+ "ts-error-scan": "tsc --noEmit",+ "prettier:format": "prettier --write **/*.{js,jsx,ts,tsx,json,css,md}",+ "lint-fix": "eslint --ext .ts src/ --fix",+ "lint-staged": "lint-staged",+ "prisma:format": "dotenv -e ../../.env prisma format ./prisma/schema.prisma",+ "prisma:generate": "dotenv -e ../../.env prisma generate --schema ./prisma/schema.prisma",+ "prisma:studio": "dotenv -e ../../.env prisma studio",+ "prisma:migrate": "dotenv -e ../../.env prisma migrate dev --schema ./prisma/schema.prisma",+ "prisma:deploy": "dotenv -e ../../.env prisma migrate deploy --schema ./prisma/schema.prisma",+ "build": "rollup -c",+ "dev": "pnpm prisma:migrate && nodemon",+ "start": "pnpm prisma:deploy && node -r esbuild-register dist/index.js",+ "start:prod": "node -r esbuild-register dist/index.js",+ "script": "node -r esbuild-register",+ "format": "prettier --write \"**/*.ts\"",+ "graph:gendot": "depcruise src --config .dependency-cruiser.cjs --output-type dot > ./doc/dependency.dot",+ "create-module": "bash _automation/commands/create-module.sh",+ "version": "pnpm run build",+ "knip": "knip"+ },+ "author": "",+ "license": "ISC",+ "devDependencies": {+ "@faker-js/faker": "^7.6.0",+ "@rollup/plugin-json": "^6.0.0",+ "@rollup/plugin-typescript": "^11.1.2",+ "@types/async": "^3.2.24",+ "@types/cors": "^2.8.13",+ "@types/ejs": "^3.1.5",+ "@types/express": "^4.17.17",+ "@types/html-to-text": "^9.0.0",+ "@types/lodash": "^4.14.197",+ "@types/node": "^20.14.2",+ "@types/supertest": "^2.0.12",+ "@types/swagger-ui-express": "^4.1.3",+ "@typescript-eslint/eslint-plugin": "^5.59.0",+ "dependency-cruiser": "^15.4.0",+ "dotenv-cli": "^10.0.0",+ "env-cmd": "^11.0.0",+ "esbuild": "^0.19.11",+ "esbuild-register": "^3.5.0",+ "eslint": "^8.38.0",+ "eslint-config-airbnb-base": "^15.0.0",+ "eslint-config-prettier": "^8.8.0",+ "eslint-config-standard-with-typescript": "^34.0.1",+ "eslint-plugin-import": "^2.27.5",+ "eslint-plugin-prettier": "^4.2.1",+ "eslint-plugin-promise": "^6.1.1",+ "husky": "^8.0.0",+ "knip": "^5.61.3",+ "lint-staged": "^13.2.1",+ "node-mocks-http": "^1.14.1",+ "nodemon": "^2.0.22",+ "prettier": "^2.8.7",+ "prisma": "^5.7.1",+ "rollup": "^3.26.0",+ "rollup-plugin-copy": "^3.5.0",+ "rollup-plugin-esbuild": "^6.1.0",+ "rollup-plugin-sourcemaps": "^0.6.3",+ "supertest": "^6.3.3",+ "tsconfig-paths": "^3.14.1",+ "typescript": "^4.9.5",+ "vitest": "^1.6.0",+ "vitest-mock-extended": "^1.3.1"+ },+ "dependencies": {+ "@aws-sdk/client-ses": "^3.421.0",+ "@prisma/client": "^5.7.1",+ "@smythos/sre": "^1.5.74",+ "axios": "^1.4.0",+ "cors": "^2.8.5",+ "date-fns": "^3.3.1",+ "dotenv": "^16.0.3",+ "dotenv-expand": "^12.0.3",+ "dotenv-flow": "^4.1.0",+ "ejs": "^3.1.9",+ "express": "^4.18.2",+ "express-async-handler": "^1.2.0",+ "express-rate-limit": "^6.7.0",+ "helmet": "^6.1.5",+ "http-status": "^1.6.2",+ "ioredis": "^5.3.2",+ "joi": "^17.9.1",+ "jose": "^4.14.4",+ "lodash": "^4.17.21",+ "node-cache": "^5.1.2",+ "qs": "^6.11.2",+ "swagger-ui-express": "^5.0.0",+ "winston": "^3.11.0",+ "winston-transport": "^4.9.0"+ },+ "knip": {+ "entry": [+ "src/index.ts",+ "src/**/*.ts"+ ],+ "project": "**/*.{js,ts}",+ "ignore": [+ "dist/**",+ "node_modules/**",+ "**/*.d.ts",+ "**/*.test.ts",+ "**/*.spec.ts"+ ],+ "ignoreDependencies": [+ "@types/*",+ "typescript"+ ],+ "ignoreBinaries": [+ "husky",+ "prettier",+ "eslint",+ "nodemon",+ "prisma"+ ],+ "rules": {+ "classMembers": "warn",+ "dependencies": "error",+ "devDependencies": "error",+ "duplicates": "error",+ "exports": "error",+ "files": "error",+ "nsExports": "error",+ "nsTypes": "error",+ "types": "error",+ "unlisted": "error"+ }+ }+}diff --git a/packages/middleware/prisma/migrations/20250820160132_init/migration.sql b/packages/middleware/prisma/migrations/20250820160132_init/migration.sqlnew file mode 100644index 00000000..ffdb287f--- /dev/null+++ b/packages/middleware/prisma/migrations/20250820160132_init/migration.sql@@ -0,0 +1,312 @@+-- CreateTable+CREATE TABLE `User` (+ `id` INTEGER NOT NULL AUTO_INCREMENT,+ `email` VARCHAR(191) NOT NULL,+ `name` VARCHAR(191) NULL,+ `avatar` MEDIUMTEXT NULL,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL,+ `teamId` VARCHAR(191) NULL,++ UNIQUE INDEX `User_email_key`(`email`),+ INDEX `User_email_idx`(`email`),+ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `UserSetting` (+ `id` INTEGER NOT NULL AUTO_INCREMENT,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `userId` INTEGER NOT NULL,+ `settingKey` VARCHAR(191) NOT NULL,+ `settingValue` MEDIUMTEXT NOT NULL,++ UNIQUE INDEX `UserSetting_userId_settingKey_key`(`userId`, `settingKey`),+ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `Team` (+ `id` VARCHAR(191) NOT NULL,+ `name` VARCHAR(191) NOT NULL,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL,+ `salt` VARCHAR(191) NOT NULL,+ `subscriptionId` VARCHAR(191) NULL,+ `externalCustomerId` VARCHAR(191) NULL,+ `referredBy` VARCHAR(191) NULL,+ `parentId` VARCHAR(191) NULL,++ UNIQUE INDEX `Team_salt_key`(`salt`),+ INDEX `Team_externalCustomerId_idx`(`externalCustomerId`),+ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `TeamSetting` (+ `id` INTEGER NOT NULL AUTO_INCREMENT,+ `settingKey` VARCHAR(191) NOT NULL,+ `settingValue` MEDIUMTEXT NOT NULL,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL,+ `teamId` VARCHAR(191) NOT NULL,++ UNIQUE INDEX `TeamSetting_teamId_settingKey_key`(`teamId`, `settingKey`),+ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `TeamRole` (+ `id` INTEGER NOT NULL AUTO_INCREMENT,+ `name` VARCHAR(191) NOT NULL,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL,+ `acl` JSON NULL,+ `canManageTeam` BOOLEAN NOT NULL DEFAULT false,+ `isOwnerRole` BOOLEAN NOT NULL DEFAULT false,+ `teamId` VARCHAR(191) NOT NULL,++ UNIQUE INDEX `TeamRole_teamId_id_key`(`teamId`, `id`),+ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `UserTeamRole` (+ `userId` INTEGER NOT NULL,+ `roleId` INTEGER NOT NULL,+ `userSpecificAcl` JSON NULL,+ `isTeamInitiator` BOOLEAN NOT NULL DEFAULT false,++ PRIMARY KEY (`userId`, `roleId`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `Subscription` (+ `id` VARCHAR(191) NOT NULL,+ `stripeId` VARCHAR(191) NOT NULL,+ `startDate` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `endDate` DATETIME(3) NULL,+ `status` ENUM('ACTIVE', 'CANCELED', 'PAST_DUE', 'UNPAID', 'TRIALING') NOT NULL,+ `updatedAt` DATETIME(3) NOT NULL,+ `properties` JSON NULL,+ `planId` INTEGER NOT NULL,+ `object` JSON NULL,++ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `Plan` (+ `id` INTEGER NOT NULL AUTO_INCREMENT,+ `stripeId` VARCHAR(191) NOT NULL,+ `priceId` VARCHAR(191) NOT NULL,+ `name` VARCHAR(191) NOT NULL,+ `friendlyName` VARCHAR(191) NULL,+ `description` MEDIUMTEXT NULL,+ `price` DOUBLE NOT NULL,+ `paid` BOOLEAN NOT NULL DEFAULT true,+ `isDefaultPlan` BOOLEAN NOT NULL DEFAULT false,+ `properties` JSON NULL,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL,+ `HTMLDescription` MEDIUMTEXT NULL,+ `HTMLFeatures` MEDIUMTEXT NULL,+ `isCustomPlan` BOOLEAN NOT NULL DEFAULT false,++ UNIQUE INDEX `Plan_name_key`(`name`),+ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `AiAgent` (+ `id` VARCHAR(191) NOT NULL,+ `name` VARCHAR(191) NOT NULL,+ `description` MEDIUMTEXT NULL,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL,+ `salt` VARCHAR(191) NOT NULL,+ `teamId` VARCHAR(191) NULL,+ `lockId` VARCHAR(191) NULL,+ `lockAt` DATETIME(3) NULL,+ `lockedByName` VARCHAR(191) NULL,+ `lastLockBeat` DATETIME(3) NULL,+ `lastLockSaveOperation` DATETIME(3) NULL,++ UNIQUE INDEX `AiAgent_salt_key`(`salt`),+ INDEX `AiAgent_createdAt_idx`(`createdAt`),+ UNIQUE INDEX `AiAgent_teamId_id_key`(`teamId`, `id`),+ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `AiAgentActivity` (+ `id` INTEGER NOT NULL AUTO_INCREMENT,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL,+ `type` VARCHAR(191) NULL,+ `name` VARCHAR(191) NOT NULL,+ `userId` INTEGER NULL,+ `aiAgentId` VARCHAR(191) NOT NULL,++ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `AiAgentContributor` (+ `id` INTEGER NOT NULL AUTO_INCREMENT,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `userId` INTEGER NOT NULL,+ `isCreator` BOOLEAN NOT NULL DEFAULT false,+ `aiAgentId` VARCHAR(191) NOT NULL,++ UNIQUE INDEX `AiAgentContributor_userId_aiAgentId_key`(`userId`, `aiAgentId`),+ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `AiAgentSettings` (+ `id` INTEGER NOT NULL AUTO_INCREMENT,+ `key` VARCHAR(191) NOT NULL,+ `value` MEDIUMTEXT NOT NULL,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL,+ `aiAgentId` VARCHAR(191) NOT NULL,++ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `AiAgentData` (+ `id` INTEGER NOT NULL AUTO_INCREMENT,+ `data` JSON NULL,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL,+ `aiAgentId` VARCHAR(191) NOT NULL,++ UNIQUE INDEX `AiAgentData_aiAgentId_key`(`aiAgentId`),+ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `AiAgentDeployment` (+ `id` VARCHAR(191) NOT NULL,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL,+ `aiAgentId` VARCHAR(191) NOT NULL,+ `aiAgentSettings` JSON NULL,+ `aiAgentData` JSON NULL,+ `majorVersion` INTEGER NOT NULL,+ `minorVersion` INTEGER NOT NULL,+ `releaseNotes` MEDIUMTEXT NULL,++ INDEX `AiAgentDeployment_id_aiAgentId_idx`(`id`, `aiAgentId`),+ UNIQUE INDEX `AiAgentDeployment_aiAgentId_majorVersion_minorVersion_key`(`aiAgentId`, `majorVersion`, `minorVersion`),+ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `AiAgentState` (+ `id` INTEGER NOT NULL AUTO_INCREMENT,+ `key` VARCHAR(191) NOT NULL,+ `value` VARCHAR(191) NOT NULL,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL,+ `aiAgentId` VARCHAR(191) NOT NULL,++ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `Embodiment` (+ `id` INTEGER NOT NULL AUTO_INCREMENT,+ `type` VARCHAR(191) NOT NULL,+ `properties` JSON NULL,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL,+ `aiAgentId` VARCHAR(191) NOT NULL,++ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- CreateTable+CREATE TABLE `AiAgentConversation` (+ `id` VARCHAR(191) NOT NULL,+ `label` VARCHAR(191) NULL,+ `createdAt` DATETIME(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3),+ `updatedAt` DATETIME(3) NOT NULL,+ `summary` MEDIUMTEXT NULL,+ `chunkSize` INTEGER NULL,+ `lastChunkID` VARCHAR(191) NULL,+ `aiAgentId` VARCHAR(191) NOT NULL,+ `teamId` VARCHAR(191) NOT NULL,+ `ownerId` INTEGER NULL,++ PRIMARY KEY (`id`)+) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;++-- AddForeignKey+ALTER TABLE `User` ADD CONSTRAINT `User_teamId_fkey` FOREIGN KEY (`teamId`) REFERENCES `Team`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `UserSetting` ADD CONSTRAINT `UserSetting_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `Team` ADD CONSTRAINT `Team_subscriptionId_fkey` FOREIGN KEY (`subscriptionId`) REFERENCES `Subscription`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `Team` ADD CONSTRAINT `Team_parentId_fkey` FOREIGN KEY (`parentId`) REFERENCES `Team`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `TeamSetting` ADD CONSTRAINT `TeamSetting_teamId_fkey` FOREIGN KEY (`teamId`) REFERENCES `Team`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `TeamRole` ADD CONSTRAINT `TeamRole_teamId_fkey` FOREIGN KEY (`teamId`) REFERENCES `Team`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `UserTeamRole` ADD CONSTRAINT `UserTeamRole_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `UserTeamRole` ADD CONSTRAINT `UserTeamRole_roleId_fkey` FOREIGN KEY (`roleId`) REFERENCES `TeamRole`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `Subscription` ADD CONSTRAINT `Subscription_planId_fkey` FOREIGN KEY (`planId`) REFERENCES `Plan`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `AiAgent` ADD CONSTRAINT `AiAgent_teamId_fkey` FOREIGN KEY (`teamId`) REFERENCES `Team`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `AiAgentActivity` ADD CONSTRAINT `AiAgentActivity_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `AiAgentActivity` ADD CONSTRAINT `AiAgentActivity_aiAgentId_fkey` FOREIGN KEY (`aiAgentId`) REFERENCES `AiAgent`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `AiAgentContributor` ADD CONSTRAINT `AiAgentContributor_userId_fkey` FOREIGN KEY (`userId`) REFERENCES `User`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `AiAgentContributor` ADD CONSTRAINT `AiAgentContributor_aiAgentId_fkey` FOREIGN KEY (`aiAgentId`) REFERENCES `AiAgent`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `AiAgentSettings` ADD CONSTRAINT `AiAgentSettings_aiAgentId_fkey` FOREIGN KEY (`aiAgentId`) REFERENCES `AiAgent`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `AiAgentData` ADD CONSTRAINT `AiAgentData_aiAgentId_fkey` FOREIGN KEY (`aiAgentId`) REFERENCES `AiAgent`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `AiAgentDeployment` ADD CONSTRAINT `AiAgentDeployment_aiAgentId_fkey` FOREIGN KEY (`aiAgentId`) REFERENCES `AiAgent`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `AiAgentState` ADD CONSTRAINT `AiAgentState_aiAgentId_fkey` FOREIGN KEY (`aiAgentId`) REFERENCES `AiAgent`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `Embodiment` ADD CONSTRAINT `Embodiment_aiAgentId_fkey` FOREIGN KEY (`aiAgentId`) REFERENCES `AiAgent`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `AiAgentConversation` ADD CONSTRAINT `AiAgentConversation_aiAgentId_fkey` FOREIGN KEY (`aiAgentId`) REFERENCES `AiAgent`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `AiAgentConversation` ADD CONSTRAINT `AiAgentConversation_teamId_fkey` FOREIGN KEY (`teamId`) REFERENCES `Team`(`id`) ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE `AiAgentConversation` ADD CONSTRAINT `AiAgentConversation_ownerId_fkey` FOREIGN KEY (`ownerId`) REFERENCES `User`(`id`) ON DELETE SET NULL ON UPDATE CASCADE;diff --git a/packages/middleware/prisma/migrations/migration_lock.toml b/packages/middleware/prisma/migrations/migration_lock.tomlnew file mode 100644index 00000000..e5a788a7--- /dev/null+++ b/packages/middleware/prisma/migrations/migration_lock.toml@@ -0,0 +1,3 @@+# Please do not edit this file manually+# It should be added in your version-control system (i.e. Git)+provider = "mysql"\ No newline at end of filediff --git a/packages/middleware/prisma/prisma-client.ts b/packages/middleware/prisma/prisma-client.tsnew file mode 100644index 00000000..8b28bb45--- /dev/null+++ b/packages/middleware/prisma/prisma-client.ts@@ -0,0 +1,45 @@+/* eslint-disable vars-on-top */+/* eslint-disable no-var */+import { PrismaClient } from '@prisma/client';++// declare global {+// var prisma: PrismaClient; // Use 'var' to declare a global variable+// }++// add prisma to the NodeJS global type+//! downgrade @types/node to 15.14.1 to avoid error on NodeJS.Global+// interface CustomNodeJsGlobal extends NodeJS.Global {+// prisma: PrismaClient;+// }++// Prevent multiple instances of Prisma Client in development++// main app prisma instance+const prisma = (global.prisma as PrismaClient) || new PrismaClient();++//* disabled for now becuse it breaks some of the current code+// TODO: enable this as soon as we have some time to fix the code+// prisma.$use(async (params, next) => { // middleware for ensuring that no "undefined" values are passed to prisma+// if (hasUndefinedValue(params.args?.where)) throw new Error(`Invalid where: ${JSON.stringify(params.args.where)}`);+// return next(params);+// });++// function hasUndefinedValue<T>(obj: T): boolean {+// if (typeof obj !== 'object' || obj === null) return false;++// for (const [key, value] of Object.entries(obj)) {+// if (value === undefined) return true;++// if (typeof value === 'object' && !Array.isArray(value)) {+// if (hasUndefinedValue(value)) return true;+// }+// }++// return false;+// }++if (process.env.NODE_ENV === 'development') {+ global.prisma = prisma;+}++export { prisma };diff --git a/packages/middleware/prisma/schema.prisma b/packages/middleware/prisma/schema.prismanew file mode 100644index 00000000..00c6ff23--- /dev/null+++ b/packages/middleware/prisma/schema.prisma@@ -0,0 +1,325 @@+generator client {+ provider = "prisma-client-js"+ binaryTargets = ["native", "linux-musl-openssl-3.0.x", "darwin-arm64"]+}++datasource db {+ provider = "mysql"+ url = env("DATABASE_URL")+}++model User {+ id Int @id @default(autoincrement())+ email String @unique+ // firstName String?+ // lastName String?+ name String?+ avatar String? @db.MediumText++ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ settings UserSetting[]++ team Team? @relation(fields: [teamId], references: [id], onDelete: SetNull)+ teamId String?++ // user role+ userTeamRole UserTeamRole[]++ agentChangeActivities AiAgentActivity[]++ agentContributions AiAgentContributor[]+ agentConversations AiAgentConversation[]++ @@index([email])+}++model UserSetting {+ id Int @id @default(autoincrement())+ createdAt DateTime @default(now())+ updatedAt DateTime @default(now()) @updatedAt+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ userId Int+ settingKey String+ settingValue String @db.MediumText++ @@unique([userId, settingKey])+}++model Team {+ id String @id @default(cuid())+ name String+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ salt String @unique @default(cuid()) // for M2M++ users User[]+ subscription Subscription? @relation(fields: [subscriptionId], references: [id], onDelete: SetNull)+ subscriptionId String?++ // stripeCustomerId String?+ externalCustomerId String?+ referredBy String?++ aiAgents AiAgent[]++ // team roles+ teamRoles TeamRole[]++ // team invitations++ teamSettings TeamSetting[]++ agentConversations AiAgentConversation[]++ // team hierarchy+ parent Team? @relation("TeamParent", fields: [parentId], references: [id], onDelete: SetNull)+ parentId String?+ subTeams Team[] @relation("TeamParent")++ @@index([externalCustomerId])+}++model TeamSetting {+ id Int @id @default(autoincrement())+ settingKey String+ settingValue String @db.MediumText+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)+ teamId String++ @@unique([teamId, settingKey])+}++model TeamRole {+ id Int @id @default(autoincrement())+ name String+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ acl Json?+ canManageTeam Boolean @default(false)++ isOwnerRole Boolean @default(false)++ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)+ teamId String++ userTeamRole UserTeamRole[]++ @@unique([teamId, id])+}++model UserTeamRole {+ userId Int+ roleId Int+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)++ sharedTeamRole TeamRole @relation(fields: [roleId], references: [id], onDelete: Cascade)+ userSpecificAcl Json?+ isTeamInitiator Boolean @default(false)++ @@id([userId, roleId])+}++enum SubscriptionStatus {+ ACTIVE+ CANCELED+ PAST_DUE+ UNPAID+ TRIALING+}++model Subscription {+ id String @id @default(cuid())+ stripeId String+ startDate DateTime @default(now())+ endDate DateTime?+ status SubscriptionStatus+ updatedAt DateTime @updatedAt++ properties Json?++ plan Plan @relation(fields: [planId], references: [id])+ planId Int++ object Json?++ team Team[]+}++model Plan {+ id Int @id @default(autoincrement())+ stripeId String+ priceId String+ name String @unique+ friendlyName String?+ description String? @db.MediumText+ price Float+ paid Boolean @default(true)+ isDefaultPlan Boolean @default(false)+ properties Json?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ HTMLDescription String? @db.MediumText+ HTMLFeatures String? @db.MediumText++ isCustomPlan Boolean @default(false)++ subscriptions Subscription[]+}++model AiAgent {+ id String @id @default(cuid())+ name String+ description String? @db.MediumText+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ salt String @unique @default(cuid()) // for M2M++ changeActivity AiAgentActivity[]+ contributors AiAgentContributor[]++ // AI Agent subscription+ team Team? @relation(fields: [teamId], references: [id], onDelete: Cascade)+ teamId String?+ embodiments Embodiment[]++ // AI Agent data+ aiAgentData AiAgentData?++ // AI Agent state+ aiAgentState AiAgentState[]+ aiAgentSettings AiAgentSettings[]++ // AI Agent Locking properties+ lockId String?+ lockAt DateTime?+ lockedByName String? // I avoided using the user model here to avoid unnecessary joins. I think the name is enough+ lastLockBeat DateTime?+ lastLockSaveOperation DateTime?++ // AI Agent deployments+ AiAgentDeployment AiAgentDeployment[]++ agentConversations AiAgentConversation[]++ @@unique([teamId, id])+ @@index([createdAt])+}++model AiAgentActivity {+ id Int @id @default(autoincrement())+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ type String?+ name String++ user User? @relation(fields: [userId], references: [id], onDelete: SetNull)+ userId Int?++ aiAgent AiAgent @relation(fields: [aiAgentId], references: [id], onDelete: Cascade)+ aiAgentId String+}++model AiAgentContributor {+ id Int @id @default(autoincrement())+ createdAt DateTime @default(now())++ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ userId Int+ isCreator Boolean @default(false)++ aiAgent AiAgent @relation(fields: [aiAgentId], references: [id], onDelete: Cascade)+ aiAgentId String++ @@unique([userId, aiAgentId])+}++model AiAgentSettings {+ id Int @id @default(autoincrement())+ key String+ value String @db.MediumText+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ aiAgent AiAgent @relation(fields: [aiAgentId], references: [id], onDelete: Cascade)+ aiAgentId String+}++model AiAgentData {+ id Int @id @default(autoincrement())+ data Json?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ aiAgent AiAgent @relation(fields: [aiAgentId], references: [id], onDelete: Cascade)+ aiAgentId String @unique+}++model AiAgentDeployment {+ id String @id @default(cuid())+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ aiAgent AiAgent @relation(fields: [aiAgentId], references: [id], onDelete: Cascade)+ aiAgentId String++ aiAgentSettings Json?+ aiAgentData Json?++ // version of the deployment+ majorVersion Int+ minorVersion Int++ releaseNotes String? @db.MediumText++ @@unique([aiAgentId, majorVersion, minorVersion])+ @@index([id, aiAgentId])+}++model AiAgentState {+ id Int @id @default(autoincrement())+ key String+ value String+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ aiAgent AiAgent @relation(fields: [aiAgentId], references: [id], onDelete: Cascade)+ aiAgentId String+}++model Embodiment {+ id Int @id @default(autoincrement())+ type String+ properties Json?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt++ aiAgent AiAgent @relation(fields: [aiAgentId], references: [id], onDelete: Cascade)+ aiAgentId String+}++model AiAgentConversation {+ id String @id @default(cuid())+ label String?+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+ summary String? @db.MediumText++ chunkSize Int?+ lastChunkID String?++ aiAgent AiAgent @relation(fields: [aiAgentId], references: [id], onDelete: Cascade)+ aiAgentId String++ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)+ teamId String++ user User? @relation(fields: [ownerId], references: [id], onDelete: SetNull)+ ownerId Int?+}diff --git a/packages/middleware/rollup.config.mjs b/packages/middleware/rollup.config.mjsnew file mode 100644index 00000000..2f1fe370--- /dev/null+++ b/packages/middleware/rollup.config.mjs@@ -0,0 +1,34 @@+import json from '@rollup/plugin-json';+import copy from 'rollup-plugin-copy';+import esbuild from 'rollup-plugin-esbuild';+import sourcemaps from 'rollup-plugin-sourcemaps';+import pkg from './package.json' with { type: 'json' };++export default {+ input: 'src/index.ts',++ output: {+ dir: 'dist',+ format: 'es',+ sourcemap: true,+ },+ plugins: [+ esbuild({ sourceMap: true }),+ json(),+ sourcemaps(),+ copy({+ targets: [{ src: ['src/views/*'], dest: 'dist/views' }],+ }),+ ],+ external: [...Object.keys(pkg.dependencies), ...Object.keys(pkg.devDependencies)],++ onwarn(warning, warn) {+ // Ignore circular deps+ if (warning.code === "CIRCULAR_DEPENDENCY") return;+ // Ignore unresolved externals+ if (warning.code === "UNRESOLVED_IMPORT") return;++ // Default handler+ warn(warning);+ }+};diff --git a/packages/middleware/src/app.ts b/packages/middleware/src/app.tsnew file mode 100644index 00000000..1b5e6c4c--- /dev/null+++ b/packages/middleware/src/app.ts@@ -0,0 +1,80 @@+import cors from 'cors';+import express from 'express';+import helmet from 'helmet';+import httpStatus from 'http-status';+import swaggerUi from 'swagger-ui-express';+import { config } from '../config/config';+import systemSwaggerDocument from '../docs/_sysapi.swagger.json';+import appSwaggerDocument from '../docs/swagger.json';+import { errorHandler } from './middlewares/error.middleware';+import { infoLogger } from './middlewares/info-logger.middleware';+import { routes } from './routes/v1';+import { systemRoutes } from './routes/v1/_sysapi';+import ApiError from './utils/apiError';++const app = express();++app.use(helmet());++// app.use(appLimiter);+// parse json request body+app.use(+ express.json({+ limit: '50mb',+ verify: (req, res, buf) => {+ // @ts-ignore+ // const url = req.originalUrl;+ // @ts-ignore+ req.rawBody = buf; // for webhooks signature verification+ },+ }),+);++if (config.variables.env !== 'production') {+ // #region server swagger docs++ // server m2m swagger docs (system routes)+ app.use('/_sysapi/api-docs', swaggerUi.serveFiles(systemSwaggerDocument, {}), swaggerUi.setup(systemSwaggerDocument));+ app.use('/api-docs', swaggerUi.serveFiles(appSwaggerDocument, {}), swaggerUi.setup(appSwaggerDocument));+ // #endregion+}++// parse urlencoded request body+app.use(express.urlencoded({ extended: true, limit: '50mb' }));+app.use(infoLogger);++app.use(+ cors({+ origin: '*',+ methods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'],+ allowedHeaders: ['Content-Type', 'Authorization'],+ exposedHeaders: ['Content-Type', 'Authorization'],+ credentials: true,+ maxAge: 86400,+ }),+);++// v1 api routes+app.use('/v1', routes);+// system/m2m routes+app.use(`/_sysapi/v1`, systemRoutes);++app.get('/health', (_req, res) => {+ res.status(httpStatus.OK).send({+ version: config.package.version,+ name: config.package.name,+ });+});++app.use((_req, _res, next) => {+ console.log(`IP ${_req.ip} tried to call ${_req.originalUrl}`);+ next(new ApiError(httpStatus.NOT_FOUND, 'Not found'));+});++// convert error to ApiError, if needed. DISABLED for now because of the problem:+// instanceof ApiError is not working in the errorConverter function as it always returns false even if the error is an instance of ApiError+// app.use(errorConverter);++app.use(errorHandler);++export { app };diff --git a/packages/middleware/src/data/model-agents.json b/packages/middleware/src/data/model-agents.jsonnew file mode 100644index 00000000..d307b931--- /dev/null+++ b/packages/middleware/src/data/model-agents.json@@ -0,0 +1,7 @@+[+ {+ "idPrefix": "model-claude-3-7-sonnet",+ "fileData": {"version":"1.0.0","id":"","name":"Claude","teamId":"","parentTeamId":"","components":[{"id":"CM740UWVJ1Y","name":"APIEndpoint","outputs":[{"name":"headers","color":"#3C89F9","index":0,"default":true},{"name":"body","color":"#3C89F9","index":1,"default":true},{"name":"query","color":"#3C89F9","index":2,"default":true},{"name":"body.query","color":"#3C89F9","index":3,"default":false}],"inputs":[{"name":"query","type":"String","friendlyInputType":"","coreInputType":"","color":"#F35063","optional":false,"index":0,"default":false}],"data":{"endpoint":"search","description":"Search the web for information based on user query","method":"POST","ai_exposed":true,"advancedModeEnabled":true,"endpointLabel":"","summary":""},"top":"0px","left":"50px","width":"","height":"","displayName":"APIEndpoint","title":"Search Web","aiTitle":"","description":"Performs a web search query"},{"id":"CM740UWVLN9","name":"WebSearch","outputs":[{"name":"Results","color":"#3C89F9","index":0,"default":true},{"name":"Images","color":"#3C89F9","index":1,"default":true},{"name":"Answer","color":"#3C89F9","index":2,"default":true}],"inputs":[{"name":"SearchQuery","type":"String","friendlyInputType":"","coreInputType":"","color":"#F35063","optional":false,"index":0,"default":true}],"data":{"sourcesLimit":"5","searchTopic":"general","includeQAs":true,"includeImages":true,"timeRange":"None","includeRawContent":true,"excludeDomains":""},"top":"0px","left":"500px","width":"","height":"","displayName":"Web Search","title":"Web Search","aiTitle":"","description":"Searches the web for results"},{"id":"CM740UWVNPR","name":"APIOutput","outputs":[{"name":"Output","color":"#3C89F9","index":0,"default":true}],"inputs":[{"name":"results","type":"Any","friendlyInputType":"","coreInputType":"","color":"#F35063","optional":false,"index":0,"default":false},{"name":"images","type":"Any","friendlyInputType":"","coreInputType":"","color":"#F35063","optional":false,"index":1,"default":false},{"name":"answer","type":"Any","friendlyInputType":"","coreInputType":"","color":"#F35063","optional":false,"index":2,"default":false}],"data":{"format":"minimal"},"top":"0px","left":"950px","width":"","height":"","displayName":"APIOutput","title":"Search Results","aiTitle":"","description":"Returns formatted search results"}],"connections":[{"sourceId":"CM740UWVJ1Y","sourceIndex":3,"targetId":"CM740UWVLN9","targetIndex":0},{"sourceId":"CM740UWVLN9","sourceIndex":0,"targetId":"CM740UWVNPR","targetIndex":0},{"sourceId":"CM740UWVLN9","sourceIndex":1,"targetId":"CM740UWVNPR","targetIndex":1},{"sourceId":"CM740UWVLN9","sourceIndex":2,"targetId":"CM740UWVNPR","targetIndex":2}],"description":"","shortDescription":"Chat with Agent Claude, powered by Anthropic's newest models and enhanced with integrated web-search capabilities.","behavior":"Claude delivers thoughtful, context-aware responses, proactively using web searches to retrieve current information when necessary. It prioritizes accuracy, clarity, and conciseness, aiming to efficiently resolve user queries with reliable data. Always provide well-formatted results from your web searches. If a query is ambiguous, ask for clarification to ensure you deliver the most relevant information. Present search results in a clear, organized manner.","ui":{"panzoom":{"currentPan":{"x":430.9609375,"y":50.8984375},"currentZoom":0.5},"agentCard":{"left":"-700px","top":"-6px"}},"introMessage":"Hi, I'm Claude. How can I help you today?","templateInfo":{"id":"claude-ma2u094fum","name":"Claude","description":"Chat with Agent Claude, powered by Anthropic's newest models and enhanced with integrated web-search capabilities.","icon":"","category":"","publish":false,"color":"#000000","imageUrl":"","docLink":"","videoLink":""}},+ "settings": [{"id":15271,"key":"avatar","value":"https://static.stage.smyth.ai/teams/166254bd32acf1f0a7d54389e331b83c/avatar-0ffe9eb6-9449-4982-822a-7b8eedbd8fed","createdAt":"2025-05-06T11:31:15.719Z","updatedAt":"2025-05-06T11:31:23.632Z","aiAgentId":""},{"id":15274,"key":"chatGptModel","value":"smythos/claude-3.7-sonnet","createdAt":"2025-05-06T11:31:18.482Z","updatedAt":"2025-05-06T11:31:50.553Z","aiAgentId":""}]+ }+]\ No newline at end of filediff --git a/packages/middleware/src/index.ts b/packages/middleware/src/index.tsnew file mode 100644index 00000000..fa8cc986--- /dev/null+++ b/packages/middleware/src/index.ts@@ -0,0 +1,78 @@+import { Server } from 'http';+import { LOGGER } from '../config/logging';+import { prisma } from '../prisma/prisma-client';+import { appEvents } from './utils/app-events';+// import { metricsManager } from './metrices';+import { writeHeapSnapshot } from 'v8';+import { config } from '../config/config';+import { app } from './app';++let server: Server | null = null;+const port = config.variables.port || 3000;+(async () => {+ try {+ // metricsManager.collectMetrices();+ // metricsManager.startExportingMetrices();++ // esablish connection to database+ await prisma.$connect();+ LOGGER.info('Connected to SQL database');++ // server = app.listen(config.variables.port, () => {+ // LOGGER.info(`Listening to port ${config.variables.port}`);+ // appEvents.emit('STARTUP', undefined); // emit startup event+ // });+ app.listen(port, () => {+ LOGGER.info(`Listening to port ${port}`);+ appEvents.emit('STARTUP', undefined); // emit startup event+ });+ appEvents.emit('STARTUP', undefined); // emit startup event+ } catch (error) {+ LOGGER.error(error);+ }+})();++const exitHandler = async () => {+ if (server) {+ appEvents.emit('SHUTDOWN', undefined); // emit shutdown event+ server.close(() => {+ LOGGER.info('Server closed');+ process.exit(1);+ });+ } else {+ process.exit(1);+ }+};++const unexpectedErrorHandler = (error: Error) => {+ LOGGER.error(error);+ exitHandler();+};++// on specific signal, take a heap snapshot using v8+process.on('SIGUSR2', () => {+ LOGGER.info('SIGUSR2 received');+ const heapSnapshotPath = `/tmp/middleware-heapdump-${Date.now()}.heapsnapshot`;+ writeHeapSnapshot(heapSnapshotPath);+ LOGGER.info(`Heap snapshot written to ${heapSnapshotPath}`);+});++process.on('uncaughtException', err => LOGGER.error(err));+process.on('unhandledRejection', err => LOGGER.error(err));+process.on('SIGTERM', () => {+ LOGGER.info('SIGTERM received');+ if (server) {+ server.close();+ }+});++setInterval(() => {+ const memoryUsage = process.memoryUsage();++ LOGGER.info(`Memory Usage at ${new Date().toLocaleTimeString()}:`);+ LOGGER.info(` RSS: ${(memoryUsage.rss / 1024 / 1024).toFixed(2)} MB`);+ LOGGER.info(` Heap Total: ${(memoryUsage.heapTotal / 1024 / 1024).toFixed(2)} MB`);+ LOGGER.info(` Heap Used: ${(memoryUsage.heapUsed / 1024 / 1024).toFixed(2)} MB`);+ LOGGER.info(` External: ${(memoryUsage.external / 1024 / 1024).toFixed(2)} MB`);+ LOGGER.info('--------------------------------------------');+}, 60_000); // Outputs every 5 secondsdiff --git a/packages/middleware/src/metrices/consts.ts b/packages/middleware/src/metrices/consts.tsnew file mode 100644index 00000000..fc44aa5d--- /dev/null+++ b/packages/middleware/src/metrices/consts.ts@@ -0,0 +1,3 @@+import { config } from '../../config/config';++export const METRIC_PREFIX = `middleware_${config.variables.env}`;diff --git a/packages/middleware/src/metrices/custom/business.custom.metrices.ts b/packages/middleware/src/metrices/custom/business.custom.metrices.tsnew file mode 100644index 00000000..af04d98a--- /dev/null+++ b/packages/middleware/src/metrices/custom/business.custom.metrices.ts@@ -0,0 +1,24 @@+// import { Counter, Gauge, Histogram } from 'prom-client';+// import { CustomMetrics } from './interface';++// class BusinessCustomMetrics extends CustomMetrics {+// public userSignupCounter: Counter;++// constructor() {+// super();+// this.userSignupCounter = new Counter({+// name: this.name('user_signup_count'),+// help: 'Counter for user signups',+// labelNames: ['status'],+// });+// }++// registerMetrics(register: { registerMetric: (metric: any) => void }) {+// console.log('Registering business custom metrics');+// register.registerMetric(this.userSignupCounter);+// }+// }++// const businessCustomMetrics = new BusinessCustomMetrics();++// export default businessCustomMetrics;diff --git a/packages/middleware/src/metrices/custom/interface.ts b/packages/middleware/src/metrices/custom/interface.tsnew file mode 100644index 00000000..efea0dc0--- /dev/null+++ b/packages/middleware/src/metrices/custom/interface.ts@@ -0,0 +1,11 @@+// import { MetricsManager } from '..';+// import { config } from '../../../config/config';+// import { METRIC_PREFIX } from '../consts';++// export abstract class CustomMetrics {+// abstract registerMetrics(register: { registerMetric: (metric: any) => void }): void;++// public name(n: string) {+// return `${METRIC_PREFIX}_${n}`;+// }+// }diff --git a/packages/middleware/src/metrices/custom/traffic.custom.metrices.ts b/packages/middleware/src/metrices/custom/traffic.custom.metrices.tsnew file mode 100644index 00000000..18da87de--- /dev/null+++ b/packages/middleware/src/metrices/custom/traffic.custom.metrices.ts@@ -0,0 +1,32 @@+// import { Counter, Gauge, Histogram } from 'prom-client';+// import { CustomMetrics } from './interface';++// class TrafficCustomMetrics extends CustomMetrics {+// public responseTime: Histogram;+// public errorCounter: Counter;++// constructor() {+// super();+// this.responseTime = new Histogram({+// name: this.name('response_time_seconds'),+// help: 'Duration of HTTP requests',+// labelNames: ['method', 'path'],+// buckets: [0.1, 0.5, 1, 1.5, 2, 3, 5, 15, 30, 60],+// });++// this.errorCounter = new Counter({+// name: this.name('error_count'),+// help: 'Counter for HTTP errors',+// labelNames: ['method', 'path', 'status'],+// });+// }++// registerMetrics(register: { registerMetric: (metric: any) => void }) {+// register.registerMetric(this.responseTime);+// register.registerMetric(this.errorCounter);+// }+// }++// const trafficCustomMetrics = new TrafficCustomMetrics();++// export default trafficCustomMetrics;diff --git a/packages/middleware/src/metrices/index.ts b/packages/middleware/src/metrices/index.tsnew file mode 100644index 00000000..91af9db5--- /dev/null+++ b/packages/middleware/src/metrices/index.ts@@ -0,0 +1,56 @@+// import { collectDefaultMetrics, Registry, Pushgateway, register } from 'prom-client';+// import trafficCustomMetrics from './custom/traffic.custom.metrices';+// import businessCustomMetrics from './custom/business.custom.metrices';+// import { config } from '../../config/config';+// import { LOGGER } from '../../config/logging';+// import { METRIC_PREFIX } from './consts';++// export class MetricsManager {+// private register: Registry;+// private interval: NodeJS.Timeout;+// private gateway: Pushgateway<'text/plain; version=0.0.4; charset=utf-8'>;++// constructor() {+// this.register = register;+// this.gateway = new Pushgateway(config.variables.PUSHGATEWAY_URL);+// }++// public get metricesRegister() {+// return this.register;+// }++// public collectMetrices() {+// collectDefaultMetrics({ register: this.metricesRegister, prefix: `${METRIC_PREFIX}_`, labels: { app: `middleware_${process.env.PORT}` } });+// trafficCustomMetrics.registerMetrics(this.metricesRegister);+// businessCustomMetrics.registerMetrics(this.metricesRegister);+// }++// public static getPrefix() {+// return `middleware_${config.variables.env}`;+// }++// public async startExportingMetrices() {+// this.interval = setInterval(() => {+// this.exportMetrices().catch(error => LOGGER.error(error));+// }, 1000 * 5); // 5 seconds+// }++// private async exportMetrices() {+// await this.gateway+// .pushAdd({+// jobName: `middleware_${config.variables.env}`,+// groupings: { app: `middleware_${process.env.PORT.substring(2)}` },+// })+// .catch(error => LOGGER.error(error));+// console.log('Metrics pushed to prometheus');+// }++// public stopExportingMetrices() {+// if (!this.interval) {+// return;+// }+// clearInterval(this.interval);+// }+// }++// export const metricsManager = new MetricsManager();diff --git a/packages/middleware/src/middlewares/error.middleware.ts b/packages/middleware/src/middlewares/error.middleware.tsnew file mode 100644index 00000000..cb82bf58--- /dev/null+++ b/packages/middleware/src/middlewares/error.middleware.ts@@ -0,0 +1,31 @@+import { ErrorRequestHandler } from 'express';+import httpStatus from 'http-status';+import { config } from '../../config/config';+// import trafficCustomMetrics from '../metrices/custom/traffic.custom.metrices';++const errorHandler: ErrorRequestHandler = (err: any, _req, res, _next: any) => {+ // eslint-disable-next-line prefer-const+ let { statusCode, message, errKey } = err;++ if (!err.isOperational) {+ statusCode = httpStatus.INTERNAL_SERVER_ERROR;+ message = httpStatus[httpStatus.INTERNAL_SERVER_ERROR];+ }++ res.locals.errorMessage = err.message;++ const response = {+ code: statusCode ?? httpStatus.INTERNAL_SERVER_ERROR,+ message: message ?? httpStatus[statusCode],+ ...(config.variables.env === 'development' && { stack: err.stack }),+ ...(errKey && { errKey }),+ };++ // LOGGER.error(new Error(`[${err.statusCode}] ${err.message} ${err.stack}`));++ // trafficCustomMetrics.errorCounter.labels({ method: _req.method, path: _req.path, status: statusCode ?? httpStatus.INTERNAL_SERVER_ERROR }).inc();++ res.status(statusCode ?? httpStatus.INTERNAL_SERVER_ERROR).send(response);+};++export { errorHandler };diff --git a/packages/middleware/src/middlewares/info-logger.middleware.ts b/packages/middleware/src/middlewares/info-logger.middleware.tsnew file mode 100644index 00000000..0dc40c26--- /dev/null+++ b/packages/middleware/src/middlewares/info-logger.middleware.ts@@ -0,0 +1,23 @@+import { NextFunction, Request, Response } from 'express';+// import trafficCustomMetrics from '../metrices/custom/traffic.custom.metrices';++export const infoLogger = (req: Request, _res: Response, next: NextFunction) => {+ // Check for the 'X-Forwarded-For' header first to get the original IP address+ const forwardedIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;++ const startHrTime = process.hrtime();+ // const endDuration = trafficCustomMetrics.responseTime.startTimer({ method: req.method, path: req.path });++ _res.on('finish', () => {+ const elapsedHrTime = process.hrtime(startHrTime);+ const elapsedTimeInSec = elapsedHrTime[0] + elapsedHrTime[1] / 1e9;+ // LOGGER.info(`${req.method} ${req.path} - ${elapsedTimeInSec} sec (${elapsedTimeInSec * 1000} ms)`);++ // endDuration();+ // trafficCustomMetrics.responseTime.observe({ method: req.method, path: req.path }, elapsedTimeInSec);+ });++ // disabled for now+ // LOGGER.info(`Request from ${forwardedIp} to ${req.originalUrl}`);+ next();+};diff --git a/packages/middleware/src/middlewares/validate.middleware.ts b/packages/middleware/src/middlewares/validate.middleware.tsnew file mode 100644index 00000000..0a573ba0--- /dev/null+++ b/packages/middleware/src/middlewares/validate.middleware.ts@@ -0,0 +1,28 @@+import { NextFunction } from 'express';+import Joi, { ObjectSchema, Schema } from 'joi';+import httpStatus from 'http-status';+import { pick } from '../utils/pick';+import ApiError from '../utils/apiError';++type SchemaObject = {+ body?: ObjectSchema<any> | Schema;+ query?: ObjectSchema<any> | Schema;+ params?: ObjectSchema<any> | Schema;+};++const validate = (schema: SchemaObject) => (req: any, _res: any, next: NextFunction) => {+ const validSchema = pick(schema, ['params', 'query', 'body']);+ const object = pick(req, Object.keys(validSchema));+ const { value, error } = Joi.compile(validSchema)+ .prefs({ errors: { label: 'key' }, abortEarly: false })+ .validate(object);++ if (error) {+ const errorMessage = error.details.map(details => details.message).join(', ');+ return next(new ApiError(httpStatus.BAD_REQUEST, errorMessage));+ }+ Object.assign(req, value);+ return next();+};++export { validate };diff --git a/packages/middleware/src/modules/ai-agent/controllers/_sysapi/ai-agent.controller.ts b/packages/middleware/src/modules/ai-agent/controllers/_sysapi/ai-agent.controller.tsnew file mode 100644index 00000000..8dcf30a1--- /dev/null+++ b/packages/middleware/src/modules/ai-agent/controllers/_sysapi/ai-agent.controller.ts@@ -0,0 +1,362 @@+import { AiAgent, AiAgentSettings, AiAgentState } from '@prisma/client';+import httpStatus from 'http-status';+import { ExpressHandler, ExpressHandlerWithParams } from '../../../../../types';+import { agentDeploymentsService, aiAgentChatsService, aiAgentService } from '../../services';++export const getAgentById: ExpressHandler<+ // IN+ {},+ {+ agent: {+ name: string;+ updatedAt: Date;+ data: any;+ [key: string]: any;+ };+ }+> = async (req, res) => {+ const { agentId } = req.params;+ const { include } = req.query;+ const includeArray: string[] = include ? (include as string).split(',') : [];++ const agent = await aiAgentService._getAgentWithSaltById(agentId, { include: includeArray });++ res.status(httpStatus.OK).json({+ message: 'Agent retrieved successfully',+ agent,+ });+};++export const getAgentByDomain: ExpressHandler<+ // IN+ {},+ {+ agent: AiAgent;+ }+> = async (req, res) => {+ const { domainName } = req.query;++ const agent = await aiAgentService.getAgentByDomain(domainName as string);++ res.status(httpStatus.OK).json({+ message: 'Agent retrieved successfully',+ agent,+ });+};++// AI AGENTS STATE++export const getState: ExpressHandlerWithParams<+ // IN+ {+ agentId: string;+ key: string;+ },+ {},+ {+ state: {+ key: string;+ value: string;+ };+ }+> = async (req, res) => {+ const { agentId, key } = req.params;+ await aiAgentService.checkAgentExistsOrThrow(agentId, null, { anonymous: true });++ const state = await aiAgentService.getState(agentId, key);++ res.status(httpStatus.OK).json({+ message: 'States retrieved successfully',+ state,+ });+};++export const createState: ExpressHandler<+ // IN+ {+ agentId: string;+ key: string;+ value: string;+ },+ {+ state: AiAgentState;+ }+> = async (req, res) => {+ const { agentId } = req.params;+ const { key, value } = req.body;++ const state = await aiAgentService.createState(agentId, key, value);++ res.status(httpStatus.OK).json({+ message: 'State created successfully',+ state,+ });+};++export const deleteState: ExpressHandlerWithParams<+ // IN+ {+ agentId: string;+ key: string;+ },+ {},+ {}+> = async (req, res) => {+ const { agentId, key } = req.params;++ await aiAgentService.deleteState(agentId, key);++ res.status(httpStatus.OK).json({+ message: 'State deleted successfully',+ });+};++export const getStates: ExpressHandlerWithParams<+ // IN+ {+ agentId: string;+ },+ {},+ {+ states: AiAgentState[];+ }+> = async (req, res) => {+ const { agentId } = req.params;+ await aiAgentService.checkAgentExistsOrThrow(agentId, null, { anonymous: true });++ const states = await aiAgentService.getStates(agentId);++ res.status(httpStatus.OK).json({+ message: 'States retrieved successfully',+ states,+ });+};++// AI AGENTS DEPLOYMENT++export const getDeploymentById: ExpressHandlerWithParams<+ {+ deploymentId: string;+ },+ {},+ {+ deployment: any;+ }+> = async (req, res) => {+ const { deploymentId } = req.params;++ const deployment = await agentDeploymentsService.getDeploymentById(deploymentId, undefined, {+ anonymous: true,+ });++ res.status(httpStatus.OK).json({+ deployment,+ });+};++export const getDeployments: ExpressHandlerWithParams<+ {+ agentId: string;+ },+ {},+ {+ deployments: any;+ }+> = async (req, res) => {+ const { agentId } = req.params;++ const deployments = await agentDeploymentsService.listDeploymentsByAgentId({+ teamId: undefined,+ aiAgentId: agentId,+ options: {+ anonymous: true,+ },+ });++ res.status(httpStatus.OK).json({+ deployments,+ });+};++export const getDeploymentByMajorMinorVersion: ExpressHandlerWithParams<+ {+ agentId: string;+ majorVersion: string;+ minorVersion: string;+ },+ {},+ {+ deployment: any;+ }+> = async (req, res) => {+ const { agentId, majorVersion, minorVersion } = req.params;++ const deployment = await agentDeploymentsService.getDeploymentByMajorMinorVersion(agentId, majorVersion, minorVersion, undefined, {+ anonymous: true,+ });++ res.status(httpStatus.OK).json({+ deployment,+ });+};++export const getAgentSettings: ExpressHandlerWithParams<+ { agentId: string },+ {},+ {+ settings: AiAgentSettings[];+ }+> = async (req, res) => {+ const { agentId } = req.params;+ await aiAgentService.checkAgentExistsOrThrow(agentId, undefined, { anonymous: true });++ const settings = await aiAgentService.getAgentSettings(agentId, undefined, { anonymous: true });+ return res.json({+ message: 'Settings retrieved successfully',+ settings,+ });+};++// #region Agent Conversations++export const getConversationById: ExpressHandlerWithParams<+ {+ conversationId: string;+ },+ {},+ {+ conversation: any;+ }+> = async (req, res) => {+ const { conversationId } = req.params;++ const conversation = await aiAgentChatsService.getConversationByIdM2M(conversationId);++ res.status(httpStatus.OK).json({+ conversation,+ });+};++export const getConversations: ExpressHandler<+ {},+ {+ conversations: any;+ }+> = async (req, res) => {+ const { ownerId, agentId } = req.query as { [key: string]: string };++ const conversations = await aiAgentChatsService.getConversationsM2M({+ query: {+ ownerId: !Number.isNaN(+ownerId) ? +ownerId : undefined,+ agentId,+ },+ });++ res.status(httpStatus.OK).json({+ conversations,+ });+};++export const getConversationsByAgentId: ExpressHandlerWithParams<+ {+ agentId: string;+ },+ {},+ {+ conversations: any;+ }+> = async (req, res) => {+ const { agentId } = req.params;++ const conversations = await aiAgentChatsService.getConversationsByAgentIdM2M(agentId);++ res.status(httpStatus.OK).json({+ conversations,+ });+};++export const createConversation: ExpressHandler<+ {+ conversation: any;+ },+ {+ conversation: any;+ }+> = async (req, res) => {+ const { conversation } = req.body;++ const newConversation = await aiAgentChatsService.createConversationM2M(conversation);++ res.status(httpStatus.CREATED).json({+ conversation: newConversation,+ });+};++export const updateConversation: ExpressHandlerWithParams<+ {+ conversationId: string;+ },+ {+ conversation: any;+ },+ {+ conversation: any;+ }+> = async (req, res) => {+ const { conversationId } = req.params;+ const { conversation } = req.body;++ const updated = await aiAgentChatsService.updateConversationM2M(conversationId, conversation);++ res.status(httpStatus.OK).json({+ message: 'Agent conversation updated successfully',+ conversation: updated,+ });+};++export const deleteConversation: ExpressHandlerWithParams<+ {+ conversationId: string;+ },+ {},+ {}+> = async (req, res) => {+ const { conversationId } = req.params;++ await aiAgentChatsService.deleteConversationM2M(conversationId);++ res.status(httpStatus.OK).json({+ message: 'Agent conversation deleted successfully',+ });+};++// #endregion Agent Conversations++export const getTeamAgents: ExpressHandlerWithParams<+ {+ teamId: string;+ },+ {},+ {+ agents: Array<any>;+ total: number;+ }+> = async (req, res) => {+ const { teamId } = req.params;+ const { deployedOnly, includeData } = req.query;++ const { agents, total } = await aiAgentService.getTeamAgents({+ teamId,+ deployedOnly: deployedOnly === true,+ pagination: {+ page: Number(req.query.page) || undefined,+ limit: Number(req.query.limit) || undefined,+ },+ includeData: includeData === true,+ });++ res.status(httpStatus.OK).json({+ agents,+ total,+ });+};diff --git a/packages/middleware/src/modules/ai-agent/controllers/ai-agent.controller.ts b/packages/middleware/src/modules/ai-agent/controllers/ai-agent.controller.tsnew file mode 100644index 00000000..948ab5fa--- /dev/null+++ b/packages/middleware/src/modules/ai-agent/controllers/ai-agent.controller.ts@@ -0,0 +1,636 @@+import { AiAgentSettings, AiAgentState } from '@prisma/client';+import { Response } from 'express';+import httpStatus from 'http-status';+import { ExpressHandler, ExpressHandlerWithParams } from '../../../../types';+import ApiError from '../../../utils/apiError';+import errKeys from '../../../utils/errorKeys';+import { authExpressHelpers } from '../../auth/helpers/auth-express.helper';+import { teamService } from '../../team/services';+import { agentDeploymentsService, aiAgentChatsService, aiAgentService, modelAgentService } from '../services';+import { checkAgentExistsOrThrow } from '../services/ai-agent.service';++export const getModelAgents: ExpressHandler<null, any> = async (req, res: Response) => {+ const teamId = authExpressHelpers.getTeamId(res);+ const agents = await modelAgentService.listModelAgents(teamId);++ return res.status(httpStatus.OK).json({+ message: 'Model Agents retrieved successfully',+ agents,+ });+};++export const getAiAgents: ExpressHandler<null, any> = async (req, res: Response) => {+ const teamId = authExpressHelpers.getTeamId(res);+ const { includeSettings, contributors, agentActivity, page, limit, search, sortField, order } = req.query;++ const { agents, total } = await aiAgentService.getAllAiAgents({+ teamId,+ include: {+ includeSettings: includeSettings === 'true',+ contributors: contributors === 'true',+ agentActivity: agentActivity === 'true',+ },+ pagination: {+ page: page ? parseInt(page as string, 10) : undefined,+ limit: limit ? parseInt(limit as string, 10) : undefined,+ },++ sort: {+ field: sortField as any,+ order: order as any,+ },+ searchTerm: search as string | undefined,+ });++ return res.status(httpStatus.OK).json({+ message: 'Ai Agents retrieved successfully',+ agents,+ total,+ });+};++export const postSaveAgent: ExpressHandler<+ {+ id: string | undefined;+ name: string;+ description: string | undefined;+ data: object;+ lockId: string | undefined;+ spaceId: string | undefined;+ },+ { agent: any }+> = async (req, res) => {+ const { id, name, data, lockId, description, spaceId } = req.body;++ const teamId = authExpressHelpers.getTeamId(res);+ const parentTeamId = authExpressHelpers.getParentTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ const agent = await aiAgentService.saveAgent({+ aiAgentId: id,+ data: {+ name,+ json: data,+ description,+ },+ teamId,+ parentTeamId,+ userId,+ lockId,+ spaceId,+ });++ res.status(httpStatus.OK).json({+ message: 'Agent saved successfully',+ agent,+ });+};++export const getAgentById: ExpressHandler<+ {},+ {+ agent: {+ name: string;+ updatedAt: Date;+ data: any;+ domain: any;+ [key: string]: any;+ };+ }+> = async (req, res) => {+ const { agentId } = req.params;+ const { include } = req.query;+ const includeArray: string[] = include ? (include as string).split(',') : [];+ const teamId = authExpressHelpers.getTeamId(res);+ const parentTeamId = authExpressHelpers.getParentTeamId(res);++ //* Special case for injecting model agents lazily (https://app.clickup.com/t/86et3e213)+ if (modelAgentService.isModelAgentId(agentId, teamId)) {+ console.log(`Acessing model agent with id ${agentId}`);+ const modelAgent = await modelAgentService.getModelAgentById(agentId, teamId, parentTeamId, { include: includeArray });+ return res.status(httpStatus.OK).json({+ message: 'Agent retrieved successfully',+ agent: modelAgent,+ });+ }++ const agent = await aiAgentService.getAgentById(agentId, null, {+ include: includeArray,+ anonymous: true,+ });++ const agentTeamId = (agent?.data as { teamId: string })?.teamId;++ const userId = authExpressHelpers.getUserId(res);++ const isDifferentTeam = agentTeamId && teamId && agentTeamId !== teamId;+ if (isDifferentTeam) {+ const hasAccess = await teamService.isUserPartOfTeam(userId, agentTeamId);++ if (!hasAccess) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Agent not found', errKeys.NOT_ALLOWED_TO_ACCESS_AGENT);+ }++ throw new ApiError(httpStatus.NOT_FOUND, 'Agent not found', `DIFFERENT_TEAM_${agentTeamId}`);+ }++ res.status(httpStatus.OK).json({+ message: 'Agent retrieved successfully',+ agent,+ });+};++export const accquireAgentLock: ExpressHandler<+ {+ agentId: string;+ },+ {+ lock: any;+ }+> = async (req, res) => {+ const { agentId } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ const lock = await aiAgentService.accquireAgentLock({+ aiAgentId: agentId,+ teamId,+ userId,+ });++ res.status(httpStatus.OK).json({+ message: 'Agent lock acquired successfully',+ lock,+ });+};++export const releaseAgentLock: ExpressHandler<+ {+ agentId: string;+ lockId: string;+ },+ {}+> = async (req, res) => {+ const { agentId, lockId } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);++ await aiAgentService.releaseAgentLock({+ aiAgentId: agentId,+ teamId,+ lockId,+ });++ res.status(httpStatus.OK).json({+ message: 'Agent lock released successfully',+ });+};++export const sendAgentLockBeat: ExpressHandler<+ {+ agentId: string;+ lockId: string;+ },+ {}+> = async (req, res) => {+ const { agentId, lockId } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);++ console.log('teamId', teamId);++ await aiAgentService.beatAgentLock({+ aiAgentId: agentId,+ teamId,+ lockId,+ });++ res.status(httpStatus.OK).json({+ message: 'Agent lock beat sent successfully',+ });+};+export const getAgentLockStatus: ExpressHandlerWithParams<+ {+ agentId: string;+ },+ {},+ {+ status: any;+ }+> = async (req, res) => {+ const { agentId } = req.params;+ const teamId = authExpressHelpers.getTeamId(res);++ const status = await aiAgentService.getAgentLockStatus({+ aiAgentId: agentId,+ teamId,+ });++ res.status(httpStatus.OK).json({+ message: 'Agent lock status sent successfully',+ status,+ });+};++export const deleteAgent: ExpressHandlerWithParams<{ agentId: string }, {}, {}> = async (req, res) => {+ const { agentId: id } = req.params;+ const teamId = authExpressHelpers.getTeamId(res);++ await aiAgentService.deleteAgent(id, teamId);++ res.status(httpStatus.OK).json({+ message: 'Agent deleted successfully',+ });+};++// AI AGENTS STATE++export const getState: ExpressHandlerWithParams<+ {+ agentId: string;+ key: string;+ },+ {},+ {+ state: {+ key: string;+ value: string;+ };+ }+> = async (req, res) => {+ const { agentId, key } = req.params;+ await checkAgentExistsOrThrow(agentId, null, { anonymous: true });++ const state = await aiAgentService.getState(agentId, key);++ res.status(httpStatus.OK).json({+ message: 'States retrieved successfully',+ state,+ });+};++export const createState: ExpressHandler<+ {+ agentId: string;+ key: string;+ value: string;+ },+ {+ state: AiAgentState;+ }+> = async (req, res) => {+ const { agentId } = req.params;+ const { key, value } = req.body;++ const state = await aiAgentService.createState(agentId, key, value);++ res.status(httpStatus.OK).json({+ message: 'State created successfully',+ state,+ });+};++export const deleteState: ExpressHandlerWithParams<+ {+ agentId: string;+ key: string;+ },+ {},+ {}+> = async (req, res) => {+ const { agentId, key } = req.params;++ await aiAgentService.deleteState(agentId, key);++ res.status(httpStatus.OK).json({+ message: 'State deleted successfully',+ });+};++// AGENT settings++export const getAgentSettings: ExpressHandlerWithParams<+ { agentId: string },+ {},+ {+ settings: AiAgentSettings[];+ }+> = async (req, res) => {+ const { agentId } = req.params;+ const teamId = authExpressHelpers.getTeamId(res);+ await checkAgentExistsOrThrow(agentId, teamId);++ const settings = await aiAgentService.getAgentSettings(agentId, teamId);+ return res.json({+ message: 'Settings retrieved successfully',+ settings,+ });+};++export const getAgentSetting: ExpressHandlerWithParams<+ {+ key: string;+ agentId: string;+ },+ {},+ {+ setting: AiAgentSettings;+ }+> = async (req, res) => {+ const { key, agentId } = req.params;+ const teamId = authExpressHelpers.getTeamId(res);++ await checkAgentExistsOrThrow(agentId, teamId);+ const setting = await aiAgentService.getAgentSetting(agentId, key, teamId);+ res.json({+ message: 'Setting retrieved successfully',+ setting,+ });+};++export const createAgentSetting: ExpressHandler<+ {+ key: string;+ value: string;+ },+ {+ setting: AiAgentSettings;+ }+> = async (req, res) => {+ const { key, value } = req.body;+ const { agentId } = req.params;+ const teamId = authExpressHelpers.getTeamId(res);++ await checkAgentExistsOrThrow(agentId, teamId);++ const newSetting = await aiAgentService.createAgentSetting(agentId, key, value, teamId);+ res.json({+ message: 'Setting updated successfully',+ setting: newSetting,+ });+};++export const deleteAgentSetting: ExpressHandlerWithParams<+ {+ key: string;+ agentId: string;+ },+ {},+ {}+> = async (req, res) => {+ const { key, agentId } = req.params;+ const teamId = authExpressHelpers.getTeamId(res);++ await checkAgentExistsOrThrow(agentId, teamId);++ await aiAgentService.deleteAgentSetting(agentId, key, teamId);+ res.json({+ message: 'Setting deleted successfully',+ });+};++// AGENT DEPLOYMENT++export const createDeployment: ExpressHandler<+ {+ version?: string | null;+ agentId: string;+ releaseNotes?: string | null;+ },+ {+ deployment: any;+ }+> = async (req, res) => {+ const { version: unformattedVersion, agentId, releaseNotes } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);++ const newDeployment = await agentDeploymentsService.createDeployment({+ aiAgentId: agentId,+ unformattedVersion,+ releaseNotes,+ teamId,+ });++ res.status(httpStatus.CREATED).json({+ deployment: newDeployment,+ });+};++export const getDeploymentById: ExpressHandlerWithParams<+ {+ deploymentId: string;+ },+ {},+ {+ deployment: any;+ }+> = async (req, res) => {+ const { deploymentId } = req.params;+ const teamId = authExpressHelpers.getTeamId(res);++ const deployment = await agentDeploymentsService.getDeploymentById(deploymentId, teamId);++ res.status(httpStatus.OK).json({+ deployment,+ });+};++export const getDeployments: ExpressHandlerWithParams<+ {+ agentId: string;+ },+ {},+ {+ deployments: any;+ }+> = async (req, res) => {+ const teamId = authExpressHelpers.getTeamId(res);+ const { agentId } = req.params;+ const { include } = req.query;+ const includeArray: string[] = include ? (include as string).split(',') : [];++ const deployments = await agentDeploymentsService.listDeploymentsByAgentId({+ teamId,+ aiAgentId: agentId,+ include: includeArray,+ });++ res.status(httpStatus.OK).json({+ deployments,+ });+};++export const getLatestDeployment: ExpressHandlerWithParams<+ {+ agentId: string;+ },+ {},+ {+ deployment: any;+ }+> = async (req, res) => {+ const teamId = authExpressHelpers.getTeamId(res);+ const { agentId } = req.params;++ const deployment = await agentDeploymentsService.getLatestAgentDeployment({+ teamId,+ aiAgentId: agentId,+ });++ res.status(httpStatus.OK).json({+ deployment,+ });+};++// #region Agent Conversations+export const getTeamConversations: ExpressHandler<+ {},+ {+ data: any;+ }+> = async (req, res) => {+ const { isOwner, page, limit, sortField, order } = req.query as { [key: string]: any };+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ const conversationsData = await aiAgentChatsService.getConversations({+ teamId,+ userId,+ query: {+ isOwner: isOwner == 'true',+ },++ sort: {+ order: order as any,+ field: sortField as any,+ },++ pagination: {+ page: page ? parseInt(page as string, 10) : undefined,+ limit: limit ? parseInt(limit as string, 10) : undefined,+ },+ });++ res.status(httpStatus.OK).json({+ data: conversationsData,+ });+};++export const getMyConversations: ExpressHandler<+ {},+ {+ conversations: any;+ }+> = async (req, res) => {+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ const conversations = await aiAgentChatsService.getMyConversations({+ teamId,+ userId,++ pagination: {+ page: req.query.page ? parseInt(req.query.page as string, 10) : undefined,+ limit: req.query.limit ? parseInt(req.query.limit as string, 10) : undefined,+ },+ });++ res.status(httpStatus.OK).json({+ conversations,+ });+};++export const createTeamConversation: ExpressHandler<+ {+ conversation: any;+ },+ {+ conversation: any;+ }+> = async (req, res) => {+ const { conversation: conversationData } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ const conversation = await aiAgentChatsService.createTeamConversation({+ teamId,+ userId,+ data: conversationData,+ });++ res.status(httpStatus.CREATED).json({+ conversation,+ });+};++export const updateTeamConversation: ExpressHandlerWithParams<+ {+ conversationId: string;+ },+ {+ conversation: any;+ },+ {}+> = async (req, res) => {+ const { conversationId } = req.params;+ const { conversation } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ await aiAgentChatsService.updateTeamConversation({+ teamId,+ userId,+ conversationId,+ data: conversation,+ });++ res.status(httpStatus.OK).json({+ message: 'Conversation updated successfully',+ });+};++export const deleteTeamConversation: ExpressHandlerWithParams<+ {+ conversationId: string;+ },+ {},+ {}+> = async (req, res) => {+ const { conversationId } = req.params;+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ await aiAgentChatsService.deleteTeamConversation({+ teamId,+ userId,+ conversationId,+ });++ res.status(httpStatus.OK).json({+ message: 'Conversation deleted successfully',+ });+};++export const getTeamConversationById: ExpressHandlerWithParams<+ {+ conversationId: string;+ },+ {},+ {+ conversation: any;+ }+> = async (req, res) => {+ const { conversationId } = req.params;+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ const conversation = await aiAgentChatsService.getTeamConversationById({+ teamId,+ userId,+ conversationId,+ });++ res.status(httpStatus.OK).json({+ conversation,+ });+};++// # endregiondiff --git a/packages/middleware/src/modules/ai-agent/interfaces.ts b/packages/middleware/src/modules/ai-agent/interfaces.tsnew file mode 100644index 00000000..a71165c6--- /dev/null+++ b/packages/middleware/src/modules/ai-agent/interfaces.ts@@ -0,0 +1,67 @@+export interface AgentData {+ version: string;+ components: Component[];+ connections: any[];+ description: string;+ debugSessionEnabled: boolean;+ ui: {+ panzoom: {+ currentPan: {+ x: number;+ y: number;+ };+ currentZoom: number;+ };+ };+}++export interface Component {+ id: string;+ name: string;+ outputs: Output[];+ inputs: Input[];+ data: ComponentData;+ top: string;+ left: string;+ width: string;+ height: string;+ displayName: string;+ title: string;+ description: string;+}++export interface Output {+ name: string;+ color: string;+ index: number;+ default: boolean;+}++export interface Input {+ name: string;+ color: string;+ optional: boolean;+ index: number;+ default: boolean;+ type?: 'Any' | 'String' | 'Number' | 'Binary';+}++export interface ComponentData {+ model?: string;+ prompt?: string;+ maxTokens?: string;+ temperature?: string;+ stopSequences?: string;+ topP?: string;+ topK?: string;+ frequencyPenalty?: string;+ presencePenalty?: string;+ endpoint?: string;+ description?: string;+ ai_exposed?: boolean;+ method?: string;+ openAiModel?: string;+ specUrl?: string;+ descForModel?: string;+ logoUrl?: string;+}diff --git a/packages/middleware/src/modules/ai-agent/routes/_sysapi/index.ts b/packages/middleware/src/modules/ai-agent/routes/_sysapi/index.tsnew file mode 100644index 00000000..5932ef6f--- /dev/null+++ b/packages/middleware/src/modules/ai-agent/routes/_sysapi/index.ts@@ -0,0 +1,52 @@+import { Router } from 'express';+import asyncHandler from 'express-async-handler';++import { validate } from '../../../../middlewares/validate.middleware';+import * as aiAgentsController from '../../controllers/_sysapi/ai-agent.controller';+import * as aiAgentValidations from '../../validations/ai-agent.validation';++const router = Router();++router.get('/ai-agent/:agentId', validate(aiAgentValidations.getAgentByIdM2M), asyncHandler(aiAgentsController.getAgentById));++// get agent by endpoint (domain, method, endpointPath)++router.get('/ai-agent', validate(aiAgentValidations.getAgentByDomain), asyncHandler(aiAgentsController.getAgentByDomain));++// AGENT DEPLOYMENT+router.get('/ai-agent/:agentId/deployments', validate(aiAgentValidations.getDeploymentsByAgentId), asyncHandler(aiAgentsController.getDeployments));++router.get('/ai-agent/deployments/:deploymentId', validate(aiAgentValidations.getDeployment), asyncHandler(aiAgentsController.getDeploymentById));++// get deployment by major and minor version+router.get(+ '/ai-agent/:agentId/deployments/:majorVersion/:minorVersion',+ validate(aiAgentValidations.getDeploymentByMajorMinorVersion),+ asyncHandler(aiAgentsController.getDeploymentByMajorMinorVersion),+);++// AGENT STATE++router.get('/ai-agent/:agentId/states', asyncHandler(aiAgentsController.getStates));+router.get('/ai-agent/:agentId/states/:key', validate(aiAgentValidations.getState), asyncHandler(aiAgentsController.getState));+router.put('/ai-agent/:agentId/states', validate(aiAgentValidations.createState), asyncHandler(aiAgentsController.createState));++router.delete('/ai-agent/:agentId/states/:key', validate(aiAgentValidations.deleteState), asyncHandler(aiAgentsController.deleteState));++// AGENT SETTINGS+router.get('/ai-agent/:agentId/settings', asyncHandler(aiAgentsController.getAgentSettings));++// #region Agent Conversations++router.get('/chats', validate(aiAgentValidations.getConversationsM2M), asyncHandler(aiAgentsController.getConversations));+router.post('/chats', validate(aiAgentValidations.createConversationM2M), asyncHandler(aiAgentsController.createConversation));+router.put('/chats/:conversationId', validate(aiAgentValidations.updateConversationM2M), asyncHandler(aiAgentsController.updateConversation));+router.delete('/chats/:conversationId', validate(aiAgentValidations.deleteConversationM2M), asyncHandler(aiAgentsController.deleteConversation));+router.get('/chats/:conversationId', validate(aiAgentValidations.getConversationByIdM2M), asyncHandler(aiAgentsController.getConversationById));++// #endregion++// Add this new route near other agent listing routes+router.get('/ai-agent/teams/:teamId', validate(aiAgentValidations.getTeamAgents), asyncHandler(aiAgentsController.getTeamAgents));++export { router as _aiAgentRouter };diff --git a/packages/middleware/src/modules/ai-agent/routes/index.ts b/packages/middleware/src/modules/ai-agent/routes/index.tsnew file mode 100644index 00000000..a9f72779--- /dev/null+++ b/packages/middleware/src/modules/ai-agent/routes/index.ts@@ -0,0 +1,117 @@+import { Router } from 'express';+import asyncHandler from 'express-async-handler';+import { validate } from '../../../middlewares/validate.middleware';+import { userAuthMiddleware } from '../../auth/middlewares/auth.middleware';+import * as aiAgentsController from '../controllers/ai-agent.controller';+import * as aiAgentValidations from '../validations/ai-agent.validation';++const router = Router();++router.get('/ai-agents/models', userAuthMiddleware, asyncHandler(aiAgentsController.getModelAgents));++router.get('/ai-agents', userAuthMiddleware, asyncHandler(aiAgentsController.getAiAgents));++router.delete('/ai-agent/:agentId', validate(aiAgentValidations.deleteAgent), userAuthMiddleware, asyncHandler(aiAgentsController.deleteAgent));++router.post('/ai-agent', [validate(aiAgentValidations.postSaveAgent), userAuthMiddleware], asyncHandler(aiAgentsController.postSaveAgent));++router.get('/ai-agent/:agentId', userAuthMiddleware, validate(aiAgentValidations.getAgentById), asyncHandler(aiAgentsController.getAgentById));++// AGENT LOCKING++router.put('/ai-agent/lock', userAuthMiddleware, validate(aiAgentValidations.accquireAgentLock), asyncHandler(aiAgentsController.accquireAgentLock));++router.put(+ '/ai-agent/lock/release',+ userAuthMiddleware,+ validate(aiAgentValidations.releaseAgentLock),+ asyncHandler(aiAgentsController.releaseAgentLock),+);++router.put(+ '/ai-agent/lock/refresh',+ userAuthMiddleware,+ validate(aiAgentValidations.sendAgentLockBeat),+ asyncHandler(aiAgentsController.sendAgentLockBeat),+);++router.get(+ '/ai-agent/:agentId/lock-status',+ userAuthMiddleware,+ validate(aiAgentValidations.getAgentLockStatus),+ asyncHandler(aiAgentsController.getAgentLockStatus),+);++// AGENT DEPLOYMENT++router.get(+ '/ai-agent/:agentId/deployments',+ userAuthMiddleware,+ validate(aiAgentValidations.getDeploymentsByAgentId),+ asyncHandler(aiAgentsController.getDeployments),+);+router.get(+ '/ai-agent/:agentId/deployments/latest',+ userAuthMiddleware,+ validate(aiAgentValidations.getLatestDeployment),+ asyncHandler(aiAgentsController.getLatestDeployment),+);++router.get(+ '/ai-agent/deployments/:deploymentId',+ userAuthMiddleware,+ validate(aiAgentValidations.getDeployment),+ asyncHandler(aiAgentsController.getDeploymentById),+);++router.post(+ '/ai-agent/deployments',+ [userAuthMiddleware, validate(aiAgentValidations.postDeployment)],+ asyncHandler(aiAgentsController.createDeployment),+);++// AGENT settings+router.get('/ai-agent/:agentId/settings', userAuthMiddleware, asyncHandler(aiAgentsController.getAgentSettings));+router.get('/ai-agent/:agentId/settings/:key', userAuthMiddleware, asyncHandler(aiAgentsController.getAgentSetting));+router.put(+ '/ai-agent/:agentId/settings',+ userAuthMiddleware,+ validate(aiAgentValidations.createAgentSetting),+ asyncHandler(aiAgentsController.createAgentSetting),+);++router.delete('/ai-agent/:agentId/settings/:key', userAuthMiddleware, asyncHandler(aiAgentsController.deleteAgentSetting));++// #region Agent Conversations++router.get('/chats', userAuthMiddleware, validate(aiAgentValidations.getTeamConversations), asyncHandler(aiAgentsController.getTeamConversations));+router.get('/chats/me', userAuthMiddleware, validate(aiAgentValidations.getMyConversations), asyncHandler(aiAgentsController.getMyConversations));++router.post(+ '/chats',+ userAuthMiddleware,+ validate(aiAgentValidations.createTeamConversation),+ asyncHandler(aiAgentsController.createTeamConversation),+);+router.put(+ '/chats/:conversationId',+ userAuthMiddleware,+ validate(aiAgentValidations.updateTeamConversation),+ asyncHandler(aiAgentsController.updateTeamConversation),+);+router.get(+ '/chats/:conversationId',+ userAuthMiddleware,+ validate(aiAgentValidations.getTeamConversationById),+ asyncHandler(aiAgentsController.getTeamConversationById),+);+router.delete(+ '/chats/:conversationId',+ userAuthMiddleware,+ validate(aiAgentValidations.deleteTeamConversation),+ asyncHandler(aiAgentsController.deleteTeamConversation),+);++// #endregion++export { router as aiAgentRouter };diff --git a/packages/middleware/src/modules/ai-agent/services/ai-agent.service.ts b/packages/middleware/src/modules/ai-agent/services/ai-agent.service.tsnew file mode 100644index 00000000..1f0e490e--- /dev/null+++ b/packages/middleware/src/modules/ai-agent/services/ai-agent.service.ts@@ -0,0 +1,1113 @@+/* eslint-disable no-nested-ternary */+/* eslint-disable no-param-reassign */+/* eslint-disable no-unsafe-optional-chaining */+import { AiAgentSettings, AiAgentState } from '@prisma/client';+import crypto from 'crypto';+import httpStatus from 'http-status';+import _ from 'lodash';+import { createLogger } from '../../../../config/logging-v2';+import { prisma } from '../../../../prisma/prisma-client';+import { PrismaTransaction } from '../../../../types';+import ApiError from '../../../utils/apiError';+import errKeys from '../../../utils/errorKeys';+import { PRISMA_ERROR_CODES, includePagination } from '../../../utils/general';++const logger = createLogger('ai-agent-service');++const AGENT_LOCK_THRESHOLDS = {+ DISCONNECTED: 20 * 1000, // 30 seconds+ STALE_LOCK: 10 * 60 * 1000, // 10 minutes+};++export const getAllAiAgents = async ({+ teamId,+ include,+ pagination,+ sort,+ options,+ searchTerm,+}: {+ teamId: string | undefined;+ include?: {+ includeSettings?: boolean;+ contributors?: boolean;+ agentActivity?: boolean;+ };+ pagination?: {+ page?: number;+ limit?: number;+ };++ sort?: {+ field?: string;+ order?: string;+ };++ searchTerm?: string;++ options?: {+ tx?: PrismaTransaction;+ };+}) => {+ const _p = options?.tx || prisma;+ const isSearching = !!searchTerm;++ const searchWhereClause = {+ OR: [+ {+ name: {+ contains: searchTerm,+ },+ },+ {+ description: {+ contains: searchTerm,+ },+ },+ ],+ };++ if (sort?.field && !['createdAt', 'updatedAt', 'name'].includes(sort?.field)) {+ sort = undefined;+ }++ if (sort?.order && !['asc', 'desc'].includes(sort?.order)) {+ sort = undefined;+ }++ let agents: any = await (_p as unknown as typeof prisma).aiAgent.findMany({+ where: {+ team: {+ id: teamId,+ },+ ...(isSearching && searchWhereClause),+ },++ orderBy: {+ ...(sort?.field && {+ [sort.field]: sort.order ?? 'asc',+ }),+ },++ ...includePagination(pagination),++ select: {+ id: true,+ name: true,+ description: true,+ aiAgentSettings: include?.includeSettings,+ ...(include?.contributors === true && {+ contributors: {+ select: {+ isCreator: true,+ user: {+ select: {+ id: true,+ name: true,+ avatar: true,+ email: true,+ },+ },+ },+ },+ }),+ createdAt: true,+ updatedAt: true,+ ...(include?.agentActivity === true && {+ changeActivity: {+ select: {+ name: true,+ type: true,+ createdAt: true,+ user: {+ select: {+ name: true,+ avatar: true,+ email: true,+ },+ },+ },+ orderBy: {+ createdAt: 'desc',+ },+ },+ }),++ lastLockBeat: true,+ lastLockSaveOperation: true,+ lockId: true,+ lockAt: true,++ _count: {+ select: {+ AiAgentDeployment: true,+ },+ },+ },+ });++ // for backward compatibility, add to each agent in the list an empty domain object+ agents = agents.map((agent: any) => {+ agent.domain = [];+ return agent;+ });++ const total = await _p.aiAgent.count({+ where: {+ teamId,+ ...(isSearching && searchWhereClause),+ },+ });++ agents = agents.map((agent: any) => {+ // exclude the lockId from the response+ const { lockId, lastLockBeat, lastLockSaveOperation, ...rest } = agent;+ return {+ ...rest,+ isLocked: agentHasValidLock(agent.lastLockBeat, agent.lastLockSaveOperation, agent.lockId),+ };+ });++ return {+ agents,+ total,+ };+};++export const saveAgent = async ({+ data,+ teamId,+ userId,+ lockId,+ spaceId,+ aiAgentId,+ parentTeamId,+}: {+ teamId: string;+ userId: number;+ lockId?: string;+ spaceId?: string;+ aiAgentId: string | undefined;+ parentTeamId: string;+ data: { name: string; json: { [key: string]: any }; description?: string; teamId?: string };+}) => {+ if (data.json) {+ data.json.teamId = teamId; // sanity check to make sure teamId of the agent is the same as the teamId of the user+ data.json.parentTeamId = parentTeamId;+ // data.json.id = aiAgentId;+ }++ if (!aiAgentId) {+ // create new agent+ // but before, delete any sensetive info from the data.json before creating to avoid an exploit where the+ // user can create an agent using other's id+ const { id, ...cleanJsonData } = data.json;+ const newAgent = await createNewAgent({+ userId,+ teamId,+ name: data.name,+ data: cleanJsonData,+ spaceId: spaceId ?? null,+ description: data.description,+ });++ return newAgent;+ }++ const runOperations = async (tx: PrismaTransaction) => {+ const agent = await tx.aiAgent.findFirst({+ where: {+ id: aiAgentId,+ teamId,+ },+ select: {+ id: true,+ teamId: true,++ lockId: true,+ },+ });++ if (!agent) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Agent does not exist');+ }++ if (agent.lockId !== lockId) {+ throw new ApiError(httpStatus.CONFLICT, 'Invalid lock id');+ }++ // sanity check to make sure the data.json.id is the same as the aiAgentId+ data.json.id = aiAgentId;++ // update existing agent+ const updated = await tx.aiAgent.update({+ where: {+ id: aiAgentId,+ },+ data: {+ name: data.name,+ description: data.description,++ //* LOCKS updates+ lastLockSaveOperation: new Date(),+ lastLockBeat: new Date(), // a save operation is considered a beat as well++ aiAgentData: {+ update: {+ data: data.json,+ },+ },++ contributors: {+ upsert: {+ where: {+ userId_aiAgentId: {+ aiAgentId,+ userId,+ },+ },+ update: {},+ create: {+ user: {+ connect: {+ id: userId,+ },+ },+ },+ },+ },+ },++ select: {+ id: true,+ name: true,+ },+ });++ return updated;+ };++ const updatedAgent = await prisma.$transaction(runOperations, {+ timeout: 30_000,+ });++ return updatedAgent;+};++export const createNewAgent = async ({+ name,+ teamId,+ data,+ userId,+ description,+ spaceId = null,+}: {+ name: string;+ teamId: string;+ data: object;+ userId: number;+ description?: string;+ spaceId: string | null;+}) => {+ const agent = await prisma.$transaction(async tx => {+ const spaceConnection = {+ space: {+ connect: {+ id: spaceId,+ },+ },+ };++ const _agent = await tx.aiAgent.create({+ data: {+ name,+ description,+ aiAgentData: {+ create: {+ data,+ },+ },++ team: {+ connect: {+ id: teamId,+ },+ },++ ...(spaceId ? spaceConnection : {}),++ contributors: {+ create: {+ user: {+ connect: {+ id: userId,+ },+ },+ isCreator: true,+ },+ },++ changeActivity: {+ create: {+ name: 'Agent created',+ type: 'agent_created',+ user: {+ connect: {+ id: userId,+ },+ },+ },+ },+ },++ select: {+ id: true,+ name: true,+ },+ });++ return _agent;+ });++ return agent;+};++export const getAgentById = async (+ aiAgentId: string,+ teamId: string | undefined,+ options: {+ anonymous?: boolean;+ include?: string[];+ },+) => {+ if (!options.anonymous && !teamId) {+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, 'Internal error');+ }++ const agent = await prisma.aiAgent.findFirst({+ where: {+ id: aiAgentId,+ ...(options.anonymous === true ? {} : { teamId }),+ },++ select: {+ aiAgentData: {+ select: {+ data: true,+ },+ },+ name: true,+ updatedAt: true,+ description: true,++ ...(options.include?.includes('team.subscription')+ ? {+ team: {+ select: {+ name: true,+ id: true,+ parentId: true,+ subscription: {+ select: {+ id: true,+ properties: true,+ },+ },+ },+ },+ }+ : {}),++ _count: {+ select: {+ AiAgentDeployment: true,+ },+ },++ lastLockBeat: true,+ lastLockSaveOperation: true,+ lockId: true,+ lockedByName: true,+ },+ });++ if (!agent) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Agent not found');+ }++ type ModifiedAgent = typeof agent & { domain: any[] };+ const modifiedAgent: ModifiedAgent = _.cloneDeep(agent) as any;+ // for backward compatibility, add to the agent an empty domain object+ modifiedAgent.domain = [];++ const { name, updatedAt, aiAgentData, domain, lockId, lastLockBeat, lastLockSaveOperation, ...rest } = modifiedAgent;++ const isLocked = agentHasValidLock(modifiedAgent.lastLockBeat, modifiedAgent.lastLockSaveOperation, modifiedAgent.lockId);++ return {+ name,+ updatedAt,+ data: aiAgentData?.data,+ domain: modifiedAgent.domain,+ isLocked,+ ...rest,+ };+};++export const getTeamAgentsCount = async (+ teamId: string,+ options?: {+ tx?: PrismaTransaction;+ },+) => {+ const _p = options?.tx || prisma;+ const count = await _p.aiAgent.count({+ where: {+ teamId,+ },+ });++ return count;+};++export const _getAgentWithSaltById = async (+ aiAgentId: string,+ {+ include,+ }: {+ include?: string[];+ },+) => {+ const agent = await prisma.aiAgent.findFirst({+ where: {+ id: aiAgentId,+ },++ select: {+ aiAgentData: {+ select: {+ data: true,+ },+ },++ ...(include?.includes('team.subscription')+ ? {+ team: {+ select: {+ subscription: {+ select: {+ id: true,+ properties: true,++ plan: {+ select: {+ name: true,+ id: true,+ properties: true,+ isDefaultPlan: true,+ },+ },+ },+ },+ },+ },+ }+ : {}),++ name: true,+ updatedAt: true,+ salt: true,+ teamId: true,++ lastLockBeat: true,+ lastLockSaveOperation: true,+ lockId: true,+ lockedByName: true,+ },+ });++ if (!agent) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Agent not found');+ }++ const isLocked = agentHasValidLock(agent.lastLockBeat, agent.lastLockSaveOperation, agent.lockId, {+ skipStaleCheck: true,+ });+ const { aiAgentData, ...rest } = agent;++ const agentData = (aiAgentData?.data || {}) as { [key: string]: any };+ // make sure the teamId is set in the aiagentData.data+ agentData.teamId = agent.teamId;++ return {+ data: agentData,+ isLocked,+ ...rest,+ };+};++export const deleteAgent = async (id: string, teamId: string) => {+ // check if the agent is locked (being edited by another user)++ const agent = await prisma.aiAgent.findFirst({+ where: {+ id,+ teamId,+ },+ select: {+ id: true,+ lockId: true,+ lastLockBeat: true,+ lastLockSaveOperation: true,+ },+ });++ if (!agent) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Agent not found');+ }++ //* for now bypass the lock check+ // if (agentHasValidLock(agent?.lastLockBeat, agent?.lastLockSaveOperation, agent?.lockId)) {+ // throw new ApiError(httpStatus.CONFLICT, 'Agent is locked');+ // }++ await prisma.aiAgent.delete({+ where: {+ id,+ teamId,+ },+ });++ return agent;+};++export const accquireAgentLock = async ({ aiAgentId, teamId, userId }: { aiAgentId: string; teamId: string; userId: number }) => {+ /*+ ALL OPERATIONS MUST BE ATOMIC++ Scenario 1: Agent is not locked+ Scenario 2: Agent is already locked by another user++ #Scenario 1 Solution:+ 1. Create a new lock+ 2. Return the lock (with its id)+++ #Scenario 2 Solution:+ 1. Check if the lock is expired (lastLockBeat + 1 minute < now [DISCONNECTED] OR lastLockSaveOperation + 10 minutes < now [STALE LOCK])+ 2. If the lock is expired, update the lock with the new user+ 3. Return the lock (with its id)++ */++ const runOperations = async (tx: PrismaTransaction) => {+ const agent = await tx.aiAgent.findFirst({+ where: {+ id: aiAgentId,+ teamId,+ },+ select: {+ id: true,+ name: true,+ lockId: true,+ lastLockBeat: true,+ lastLockSaveOperation: true,+ },+ });++ const caller = await tx.user.findUniqueOrThrow({+ where: {+ id: userId,+ },+ select: {+ id: true,+ name: true,+ },+ });++ if (!agent) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Agent not found');+ }++ if (!agent.lockId || !agent.lastLockBeat || !agent.lastLockSaveOperation) {+ // Scenario 1+ const agentWithLock = await tx.aiAgent.update({+ where: {+ id: aiAgentId,+ },++ data: {+ lockId: crypto.randomBytes(16).toString('hex'),+ lockAt: new Date(),+ lockedByName: caller?.name,+ lastLockBeat: new Date(),+ lastLockSaveOperation: new Date(), // this is the first time we are saving the lock+ },++ select: {+ lockAt: true,+ lockId: true,+ },+ });++ logger.info(`A new agent lock accquired for agent ${aiAgentId} because there was no current lock`);++ return {+ id: agentWithLock.lockId,+ timestamp: agentWithLock.lockAt,+ };+ }++ // Scenario 2++ if (!agentHasValidLock(agent.lastLockBeat, agent.lastLockSaveOperation, agent.lockId)) {+ // release the lock+ const agentWithLock = await tx.aiAgent.update({+ where: {+ id: aiAgentId,+ },++ data: {+ lockId: crypto.randomBytes(16).toString('hex'),+ lockAt: new Date(),+ lockedByName: caller?.name ?? 'Unknown',+ lastLockBeat: new Date(),+ lastLockSaveOperation: new Date(), // this is the first time we are saving the lock+ },++ select: {+ lockAt: true,+ lockId: true,+ },+ });++ logger.info(+ `A new agent lock accquired for agent ${aiAgentId} because the current agent lock was expired and another accquire lock req was called `,+ );++ return {+ id: agentWithLock.lockId,+ timestamp: agentWithLock.lockAt,+ };+ }++ // lock is still valid+ logger.info(`Failed to accquire agent lock for agent ${aiAgentId} because the current lock is still valid`);+ throw new ApiError(httpStatus.CONFLICT, 'Agent is locked', errKeys.AGENT_LOCK_FAIL);+ };++ try {+ const lock = await prisma.$transaction(runOperations);++ return lock;+ } catch (error: any) {+ if (error?.isApiError) {+ throw error;+ }+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, 'Failed to acquire agent lock', errKeys.AGENT_LOCK_FAIL);+ }+};++export const releaseAgentLock = async ({ aiAgentId, teamId, lockId }: { aiAgentId: string; teamId: string; lockId: string }) => {+ const runOperations = async (tx: PrismaTransaction) => {+ const agent = await tx.aiAgent.findFirst({+ where: {+ id: aiAgentId,+ teamId,+ },+ select: {+ id: true,+ lockId: true,+ },+ });++ if (!agent) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Agent not found');+ }++ if (!agent.lockId) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Agent is not locked');+ }++ if (agent.lockId !== lockId) {+ throw new ApiError(httpStatus.CONFLICT, 'Invalid lock id');+ }++ const released = await tx.aiAgent.update({+ where: {+ id: aiAgentId,+ },+ data: {+ lockId: null,+ lockAt: null,+ lockedByName: null,+ lastLockBeat: null,+ lastLockSaveOperation: null,+ },++ select: null,+ });++ return released;+ };++ try {+ await prisma.$transaction(runOperations);+ } catch (error: any) {+ if (error?.isApiError) {+ throw error;+ }++ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, 'Failed to release agent lock');+ }+};++export const beatAgentLock = async ({ aiAgentId, teamId, lockId }: { aiAgentId: string; teamId: string; lockId: string }) => {+ try {+ const updated = await prisma.aiAgent.update({+ where: {+ id: aiAgentId,+ teamId,+ lockId,+ },+ data: {+ lastLockBeat: new Date(),+ },++ select: null,+ });++ return updated;+ } catch (error: any) {+ console.log('error', error);+ if (error?.code === PRISMA_ERROR_CODES.NON_EXISTENT_RECORD) {+ throw new ApiError(httpStatus.NOT_FOUND, 'The specified agent was not found or the provided lock ID is invalid.', errKeys.AGENT_LOCK_FAIL);+ }+ throw new ApiError(httpStatus.BAD_REQUEST, error.message ?? 'Unable to update agent lock status', errKeys.AGENT_LOCK_FAIL);+ }+};++export const getAgentLockStatus = async ({ aiAgentId, teamId }: { aiAgentId: string; teamId: string }) => {+ const agent = await prisma.aiAgent.findFirst({+ where: {+ id: aiAgentId,+ teamId,+ },+ select: {+ id: true,+ lockId: true,+ lastLockBeat: true,+ lastLockSaveOperation: true,+ },+ });++ if (!agent) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Agent not found');+ }++ const isLocked = agentHasValidLock(agent.lastLockBeat, agent.lastLockSaveOperation, agent.lockId);++ return {+ isLocked,+ };+};++function agentHasValidLock(+ lastBeat: Date | null | undefined,+ lastSave: Date | null | undefined,+ lockId: string | null | undefined,+ options?: {+ skipStaleCheck?: boolean;+ },+) {+ if (!lastBeat || !lastSave || !lockId) {+ return false;+ }+ const now = new Date();+ const lastBeatThreshold = new Date(lastBeat.getTime() + AGENT_LOCK_THRESHOLDS.DISCONNECTED);+ const lastSaveThreshold = new Date(lastSave.getTime() + AGENT_LOCK_THRESHOLDS.STALE_LOCK);++ return now < lastBeatThreshold && lockId !== null && (options?.skipStaleCheck || now < lastSaveThreshold);+}++export const checkAgentExistsOrThrow = async (+ aiAgentId: string,+ teamId: string | undefined | null,+ options?: {+ anonymous?: boolean;+ tx?: PrismaTransaction;+ },+) => {+ // eslint-disable-next-line no-underscore-dangle+ const _prisma = options?.tx ? options.tx : prisma;+ const agent = await _prisma.aiAgent.findFirst({+ where: {+ id: aiAgentId,+ ...(options?.anonymous === true ? {} : { teamId }),+ },+ select: {+ id: true,+ teamId: true,+ },+ });++ if (!agent) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Agent does not exist');+ }++ return agent;+};++// M2M call+export const getAgentByDomain = async (domain: string) => {+ // DO NOT REMOVE for backward compatibility++ throw new ApiError(httpStatus.NOT_FOUND, 'Agent not found');+};++// M2M: AGENT states+export async function getStates(aiAgentId: string): Promise<AiAgentState[]> {+ return prisma.aiAgentState.findMany({ where: { aiAgentId } });+}++export async function createState(agentId: string, key: string, value: string): Promise<AiAgentState> {+ const existingState = await prisma.aiAgentState.findFirst({+ where: {+ key,+ aiAgentId: agentId,+ },+ });++ if (existingState) {+ return prisma.aiAgentState.update({+ where: {+ id: existingState.id,+ },+ data: {+ value,+ },+ });+ }++ return prisma.aiAgentState.create({+ data: {+ aiAgent: { connect: { id: agentId } },+ key,+ value,+ },+ });+}++export async function getState(agentId: string, stateKey: string): Promise<AiAgentState> {+ const setting = await prisma.aiAgentState.findFirst({+ where: {+ key: stateKey,+ aiAgentId: agentId,+ },+ });++ if (!setting) {+ throw new ApiError(404, 'State not found');+ }++ return setting;+}++export async function deleteState(agentId: string, stateKey: string) {+ const aiAgentState = await prisma.aiAgentState.findFirst({+ where: {+ aiAgentId: agentId,+ key: stateKey,+ },++ select: {+ key: true,+ id: true,+ },+ });++ if (!aiAgentState) {+ throw new ApiError(404, 'State not found');+ }++ const deleted = await prisma.aiAgentState.delete({+ where: {+ id: aiAgentState.id,+ },+ });++ return deleted;+}++// AGENT settings+export async function getAgentSettings(+ aiAgentId: string,+ teamId: string | undefined | null,+ options?: {+ anonymous?: boolean;+ },+): Promise<AiAgentSettings[]> {+ return prisma.aiAgentSettings.findMany({+ where: {+ aiAgent: {+ id: aiAgentId,+ ...(options?.anonymous === true ? {} : { teamId }),+ },+ },+ });+}++export async function createAgentSetting(aiAgentId: string, key: string, value: string, teamId: string): Promise<AiAgentSettings> {+ const existingSetting = await prisma.aiAgentSettings.findFirst({+ where: {+ key,+ aiAgent: {+ id: aiAgentId,+ teamId,+ },+ },+ });++ if (existingSetting) {+ return prisma.aiAgentSettings.update({+ where: {+ id: existingSetting.id,+ },+ data: {+ value,+ },+ });+ }++ return prisma.aiAgentSettings.create({+ data: {+ aiAgent: { connect: { id: aiAgentId } },+ key,+ value,+ },+ });+}++export async function getAgentSetting(aiAgentId: string, key: string, teamId: string): Promise<AiAgentSettings> {+ const setting = await prisma.aiAgentSettings.findFirst({+ where: {+ key,+ aiAgent: {+ id: aiAgentId,+ teamId,+ },+ },+ });++ if (!setting) {+ throw new ApiError(404, 'Setting not found');+ }++ return setting;+}++export async function deleteAgentSetting(aiAgentId: string, key: string, teamId: string) {+ const setting = await prisma.aiAgentSettings.findFirst({+ where: {+ key,+ aiAgent: {+ id: aiAgentId,+ teamId,+ },+ },+ select: {+ key: true,+ id: true,+ },+ });++ if (!setting) {+ throw new ApiError(404, 'Setting not found');+ }++ const deleted = await prisma.aiAgentSettings.delete({+ where: {+ id: setting.id,+ key,+ },+ });++ return deleted;+}++export const getTeamAgents = async ({+ teamId,+ deployedOnly = false,+ includeData = false,+ pagination,+}: {+ teamId: string;+ deployedOnly?: boolean;+ includeData?: boolean;+ pagination?: {+ page?: number;+ limit?: number;+ };+}) => {+ const whereClause = {+ teamId,+ ...(deployedOnly && {+ AiAgentDeployment: {+ some: {}, // if there are any deployments, this agent is considered deployed+ },+ }),+ };++ const agents = await prisma.aiAgent.findMany({+ where: whereClause,+ ...includePagination(pagination),+ select: {+ id: true,+ name: true,+ description: true,+ createdAt: true,+ updatedAt: true,++ _count: {+ select: {+ AiAgentDeployment: true,+ },+ },+ ...(includeData && {+ aiAgentData: {+ select: {+ data: true,+ },+ },+ }),+ },+ orderBy: {+ createdAt: 'desc',+ },+ });++ type ModifiedAgent = (typeof agents)[0] & { domain: any[] };+ let modifiedAgents: ModifiedAgent[] = _.cloneDeep(agents) as any;++ // for backward compatibility, add to each agent in the list an empty domain object+ modifiedAgents = modifiedAgents.map((agent: ModifiedAgent) => {+ agent.domain = [];+ return agent;+ });++ const total = await prisma.aiAgent.count({+ where: whereClause,+ });++ // Transform the response to include the deployed flag+ const transformedAgents = modifiedAgents.map(agent => ({+ ...agent,+ deployed: agent._count.AiAgentDeployment > 0,+ _count: undefined, // Remove the _count field from the response+ }));++ return {+ agents: transformedAgents,+ total,+ };+};diff --git a/packages/middleware/src/modules/ai-agent/services/chat.ai-agent.service.ts b/packages/middleware/src/modules/ai-agent/services/chat.ai-agent.service.tsnew file mode 100644index 00000000..d2eae94f--- /dev/null+++ b/packages/middleware/src/modules/ai-agent/services/chat.ai-agent.service.ts@@ -0,0 +1,540 @@+/* eslint-disable no-param-reassign */+import httpStatus from 'http-status';+import { prisma } from '../../../../prisma/prisma-client';+import ApiError from '../../../utils/apiError';+import errKeys from '../../../utils/errorKeys';+import { includePagination } from '../../../utils/general';++// #region User-level+export async function getConversations({+ teamId,+ userId,+ query,+ sort,+ pagination,+}: {+ teamId: string;+ userId: number;+ query?: {+ isOwner?: boolean;+ };+ pagination?: {+ page?: number;+ limit?: number;+ };+ sort?: {+ order?: 'asc' | 'desc';+ field?: 'createdAt' | 'updatedAt' | 'label';+ };+}): Promise<any> {+ if (sort?.field && !['createdAt', 'updatedAt', 'label'].includes(sort?.field)) {+ sort = undefined;+ }++ if (sort?.order && !['asc', 'desc'].includes(sort?.order)) {+ sort = undefined;+ }++ const whereClause = {+ teamId,+ ownerId: query?.isOwner ? userId : undefined,+ };++ const conversations = await prisma.aiAgentConversation.findMany({+ where: whereClause,++ orderBy: {+ ...(sort?.field && {+ [sort.field]: sort.order ?? 'asc',+ }),+ },++ ...includePagination(pagination),++ select: {+ id: true,+ aiAgentId: true,+ chunkSize: true,+ lastChunkID: true,+ label: true,+ createdAt: true,+ updatedAt: true,+ summary: true,+ teamId: true,+ },+ });++ const total = await prisma.aiAgentConversation.count({+ where: whereClause,+ });++ return {+ total,+ conversations,+ };+}++export async function getMyConversations({+ teamId,+ userId,+ pagination,+}: {+ teamId: string;+ userId: number;+ pagination?: { page?: number; limit?: number };+}) {+ const conversations = await prisma.aiAgentConversation.findMany({+ where: {+ teamId,+ ownerId: userId,+ },++ ...includePagination(pagination),++ select: {+ id: true,+ aiAgentId: true,+ chunkSize: true,+ lastChunkID: true,+ label: true,+ createdAt: true,+ updatedAt: true,+ summary: true,+ teamId: true,+ },+ });++ return conversations;+}++export async function createTeamConversation({+ teamId,+ userId,+ data,+}: {+ teamId: string;+ userId: number;+ data: {+ label?: string;+ summary?: string;+ aiAgentId: string;+ chunkSize?: number;+ lastChunkID?: string;+ };+}) {+ const agent = await prisma.aiAgent.findFirst({+ where: {+ id: data.aiAgentId,+ teamId,+ },+ select: { teamId: true },+ });++ if (!agent) {+ throw new ApiError(404, 'Agent not found');+ }++ console.log(data.aiAgentId);+ const newConversation = await prisma.aiAgentConversation.create({+ data: {+ teamId,+ ownerId: userId,+ label: data.label,+ summary: data.summary,+ aiAgentId: data.aiAgentId,+ chunkSize: data.chunkSize,+ lastChunkID: data.lastChunkID,+ },++ select: {+ id: true,+ aiAgentId: true,+ chunkSize: true,+ lastChunkID: true,+ label: true,+ createdAt: true,+ updatedAt: true,+ summary: true,+ },+ });++ return newConversation;+}++export async function updateTeamConversation({+ teamId,+ userId,+ conversationId,+ data,+}: {+ teamId: string;+ userId: number;+ conversationId: string;+ data: {+ label?: string;+ summary?: string;+ };+}) {+ const existing = await prisma.aiAgentConversation.findFirst({+ where: {+ id: conversationId,+ teamId,+ ownerId: userId,+ },+ select: { ownerId: true, id: true },+ });++ if (!existing) {+ throw new ApiError(404, 'Agent conversation not found');+ }++ if (existing.ownerId !== userId) {+ throw new ApiError(403, 'You do not own this conversation', errKeys.UNAUTHORIZED_ACTION);+ }++ const updated = await prisma.aiAgentConversation.update({+ where: {+ id: conversationId,+ teamId,+ ownerId: userId,+ },+ data: {+ label: data.label,+ summary: data.summary,+ },++ select: {+ id: true,+ aiAgentId: true,+ chunkSize: true,+ lastChunkID: true,+ label: true,+ createdAt: true,+ updatedAt: true,+ summary: true,+ },+ });++ return updated;+}++export async function deleteTeamConversation({ teamId, userId, conversationId }: { teamId: string; userId: number; conversationId: string }) {+ const existing = await prisma.aiAgentConversation.findFirst({+ where: {+ id: conversationId,+ teamId,+ },+ select: { ownerId: true, id: true },+ });++ if (!existing) {+ throw new ApiError(404, 'Agent conversation not found');+ }++ if (existing.ownerId !== userId) {+ throw new ApiError(403, 'You do not own this conversation', errKeys.UNAUTHORIZED_ACTION);+ }++ const deleted = await prisma.aiAgentConversation.delete({+ where: {+ id: conversationId,+ },+ });++ return deleted;+}++export async function getTeamConversationById({ teamId, userId, conversationId }: { teamId: string; userId: number; conversationId: string }) {+ const conversation = await prisma.aiAgentConversation.findFirst({+ where: {+ id: conversationId,+ teamId,+ },++ select: {+ id: true,+ aiAgentId: true,+ chunkSize: true,+ lastChunkID: true,+ label: true,+ createdAt: true,+ updatedAt: true,+ summary: true,+ },+ });++ if (!conversation) {+ throw new ApiError(404, 'Agent conversation not found');+ }++ return conversation;+}++// #region M2M++export async function createConversationM2M(data: {+ label?: string;+ summary?: string;+ teamId: string;+ ownerId?: number;+ aiAgentId: string;+ chunkSize?: number;+ lastChunkID?: string;+}): Promise<any> {+ const team = await prisma.team.findFirst({+ where: {+ id: data.teamId,+ },+ select: { id: true },+ });++ if (!team) {+ throw new ApiError(404, 'Team not found');+ }++ const agent = await prisma.aiAgent.findFirst({+ where: {+ id: data.aiAgentId,+ },+ select: { teamId: true },+ });++ if (!agent) {+ throw new ApiError(404, 'Agent not found');+ }++ if (agent.teamId !== data.teamId) {+ throw new ApiError(400, 'Agent does not belong to the given team');+ }++ if (data.ownerId !== undefined) {+ const user = await prisma.user.findFirst({+ where: {+ id: data.ownerId,+ },+ select: {+ userTeamRole: {+ where: {+ sharedTeamRole: {+ teamId: data.teamId,+ },+ },+ select: {+ sharedTeamRole: {+ select: {+ teamId: true,+ },+ },+ },+ },+ },+ });++ if (!user) {+ throw new ApiError(404, 'User not found');+ }++ const matchingTeamId = user.userTeamRole?.[0]?.sharedTeamRole?.teamId;+ if (!matchingTeamId) {+ throw new ApiError(400, 'User does not belong to the given team');+ }+ }++ return prisma.aiAgentConversation.create({+ data,++ select: {+ id: true,+ aiAgentId: true,+ ownerId: true,+ chunkSize: true,+ lastChunkID: true,+ label: true,+ createdAt: true,+ updatedAt: true,+ summary: true,+ teamId: true,+ },+ });+}++export async function updateConversationM2M(+ id: string,+ data: {+ ownerId?: number;+ chunkSize?: number;+ lastChunkID?: string;+ label?: string;+ summary?: string;+ },+): Promise<any> {+ const existing = await prisma.aiAgentConversation.findFirst({+ where: {+ id,+ },+ select: { aiAgentId: true, teamId: true },+ });++ if (!existing) {+ throw new ApiError(404, 'Agent conversation not found');+ }++ if (data.ownerId) {+ const user = await prisma.user.findFirst({+ where: {+ id: data.ownerId,+ },+ select: {+ userTeamRole: {+ where: {+ sharedTeamRole: {+ teamId: existing.teamId,+ },+ },+ select: {+ sharedTeamRole: {+ select: {+ teamId: true,+ },+ },+ },+ },+ },+ });++ if (!user) {+ throw new ApiError(404, 'User not found');+ }++ const matchingTeamId = user.userTeamRole?.[0]?.sharedTeamRole?.teamId;+ if (!matchingTeamId) {+ throw new ApiError(400, 'User does not belong to the team that owns the conversation');+ }+ }++ const updated = await prisma.aiAgentConversation.update({+ where: {+ id,+ },+ data,++ select: {+ id: true,+ aiAgentId: true,+ ownerId: true,+ chunkSize: true,+ lastChunkID: true,+ label: true,+ createdAt: true,+ updatedAt: true,+ summary: true,+ teamId: true,+ },+ });++ return updated;+}++export async function getConversationByIdM2M(id: string): Promise<any> {+ const conversation = await prisma.aiAgentConversation.findFirst({+ where: {+ id,+ },++ select: {+ id: true,+ aiAgentId: true,+ ownerId: true,+ chunkSize: true,+ lastChunkID: true,+ label: true,+ createdAt: true,+ updatedAt: true,+ summary: true,+ teamId: true,+ },+ });++ if (!conversation) {+ throw new ApiError(404, 'Agent conversation not found');+ }++ return conversation;+}++export async function getConversationsM2M({+ query,+}: {+ query?: {+ ownerId?: number;+ agentId?: string;+ };+}): Promise<any> {+ const conversations = await prisma.aiAgentConversation.findMany({+ where: {+ ownerId: query?.ownerId,+ aiAgentId: query?.agentId,+ },++ select: {+ id: true,+ aiAgentId: true,+ ownerId: true,+ chunkSize: true,+ lastChunkID: true,+ label: true,+ createdAt: true,+ updatedAt: true,+ summary: true,+ teamId: true,+ },+ });++ return conversations;+}++export async function getConversationsByAgentIdM2M(agentId: string): Promise<any> {+ const conversations = await prisma.aiAgentConversation.findMany({+ where: {+ aiAgentId: agentId,+ },++ select: {+ id: true,+ aiAgentId: true,+ ownerId: true,+ chunkSize: true,+ lastChunkID: true,+ label: true,+ createdAt: true,+ updatedAt: true,+ summary: true,+ teamId: true,+ },+ });++ return conversations;+}++export async function deleteConversationM2M(id: string) {+ const existing = await prisma.aiAgentConversation.findFirst({+ where: {+ id,+ },+ select: { id: true },+ });++ if (!existing) {+ throw new ApiError(404, 'Agent conversation not found');+ }++ const deleted = await prisma.aiAgentConversation.delete({+ where: {+ id,+ },+ });++ return deleted;+}++// #endregiondiff --git a/packages/middleware/src/modules/ai-agent/services/deployments/deployment.ai-agent.service.ts b/packages/middleware/src/modules/ai-agent/services/deployments/deployment.ai-agent.service.tsnew file mode 100644index 00000000..78f8c1fe--- /dev/null+++ b/packages/middleware/src/modules/ai-agent/services/deployments/deployment.ai-agent.service.ts@@ -0,0 +1,433 @@+/* eslint-disable no-underscore-dangle */+/* eslint-disable no-restricted-syntax */+import httpStatus from 'http-status';+import { aiAgentService } from '..';+import { prisma } from '../../../../../prisma/prisma-client';+import { PrismaTransaction } from '../../../../../types';+import { versionUtils } from '../../../../utils';+import ApiError from '../../../../utils/apiError';+import { AbstractDeployer } from './strategies/AbstractDeployer';+import { SmythOsDeployer } from './strategies/SmythOsDeployer';++/*+ Intro:+ - creates deployments for ai-agents with versioning+ Defining the services:+ - createDeployment+ - getDeployment+ - getDeployments+++ */++export const createDeployment = async ({+ aiAgentId,+ unformattedVersion,+ teamId,+ releaseNotes,+}: {+ aiAgentId: string;+ unformattedVersion?: string | null;+ releaseNotes?: string | null;+ teamId: string;+}) => {+ /**+ * Pre-conditions:+ * 1. check agent exists+ * 2. check version is valid+ * 3. check version is not already deployed (must be higher than previous version)+ * 4. (DISABLED) check if the agent data and settings are identical to the previous version, if so, don't create a new deployment+ */++ const deployment = await prisma.$transaction(+ async tx => {+ const aiAgentSnapshot = await tx.aiAgent.findUnique({+ where: {+ teamId_id: {+ teamId,+ id: aiAgentId,+ },+ },+ select: {+ aiAgentData: {+ select: {+ data: true,+ },+ },+ aiAgentSettings: {+ select: {+ key: true,+ value: true,+ },+ },+ },+ });+ const snapshotData = aiAgentSnapshot?.aiAgentData?.data as { version: string } | null;++ if (!aiAgentSnapshot) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Agent not found');+ }++ // check if this agent is the first time to be deployed, if so, check QUOTA++ const depCount = await tx.aiAgentDeployment.count({+ where: {+ aiAgentId,+ },+ });++ let _unformattedVersion = unformattedVersion;++ if (!unformattedVersion) {+ const nextVersionComponents = await fetchNextVersion({+ aiAgentId,+ tx,+ });+ _unformattedVersion = versionUtils.buildUnformattedVersion(nextVersionComponents);+ }++ const { major, minor } = versionUtils.extractVersionComponents(_unformattedVersion);++ // get a bigger or equal major version and the biggest minor version++ const conflictingRecord = await tx.aiAgentDeployment.findFirst({+ where: {+ aiAgentId,+ OR: [+ {+ majorVersion: {+ equals: major,+ },+ minorVersion: {+ gte: minor,+ },+ },+ {+ majorVersion: {+ gt: major,+ },+ },+ ],+ },+ });++ if (conflictingRecord) {+ throw new ApiError(httpStatus.CONFLICT, 'This version is already deployed or is lower than the latest version');+ }++ /**+ * Cases to reject a version:+ * - an existing existing with the same major and the minor equals to or higher than the existing record minor+ * - an existing record with a higher major+ */++ let distribution: { url: string; name: string; id: string } = {+ url: '',+ name: '',+ id: '',+ };++ // TODO: later, we will add more deployment strategies to AWS, GCP, etc.+ const deploymentStrategy: AbstractDeployer = new SmythOsDeployer();++ const _deploymentResponse = deploymentStrategy.deploy({+ distribution,+ teamId,+ aiAgent: {+ settings: aiAgentSnapshot.aiAgentSettings,+ snapshotData: snapshotData || { version: '1.0.0' },+ id: aiAgentId,+ },+ payload: {+ releaseNotes: releaseNotes || '',+ versionComponents: {+ major,+ minor,+ },+ },+ tx,+ });++ return _deploymentResponse;+ },+ { timeout: 60_000 },+ );++ return deployment;+};++export const getDeploymentById = async (+ deploymentId: string,+ teamId?: string,+ options?: {+ anonymous?: boolean;+ },+) => {+ const deployment = await prisma.aiAgentDeployment.findFirst({+ where: {+ id: deploymentId,+ ...(options?.anonymous+ ? {}+ : {+ aiAgent: {+ team: {+ id: teamId as string,+ },+ },+ }),+ },++ select: {+ id: true,+ aiAgent: {+ select: {+ name: true,+ },+ },+ majorVersion: true,+ minorVersion: true,+ aiAgentId: true,+ aiAgentData: true,+ aiAgentSettings: true,+ createdAt: true,+ updatedAt: true,+ releaseNotes: true,+ },+ });++ if (!deployment) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Deployment not found');+ }++ return deployment;+};++export const listDeploymentsByAgentId = async ({+ teamId,+ aiAgentId,+ options,+ include = [],+}: {+ teamId?: string;+ aiAgentId: string;+ options?: {+ anonymous?: boolean;+ };+ include?: string[];+}) => {+ await aiAgentService.checkAgentExistsOrThrow(aiAgentId, teamId, {+ anonymous: options?.anonymous,+ });++ let deployments = await prisma.aiAgentDeployment.findMany({+ where: {+ aiAgent: {+ id: aiAgentId,+ ...(options?.anonymous+ ? {}+ : {+ team: {+ id: teamId as string,+ },+ }),+ },+ },+ orderBy: {+ createdAt: 'desc',+ },+ select: {+ createdAt: true,+ id: true,+ majorVersion: true,+ minorVersion: true,+ aiAgentId: true,+ releaseNotes: true,+ aiAgent: {+ select: {+ name: true,+ },+ },++ ...(include?.includes('aiAgentData')+ ? {+ aiAgentData: true,+ }+ : {}),+ },+ });++ // for backward compatibility, add to each deployment an empty domain object+ if (include?.includes('domain')) {+ deployments = deployments.map((deployment: any) => {+ (deployment.aiAgent as any).domain = [];+ return deployment;+ });+ }++ const deploymentsWithUnformattedVersion: {+ createdAt: Date;+ id: string;+ majorVersion: number;+ minorVersion: number;+ aiAgentId: string;+ version: string;+ }[] = deployments.map(deployment => ({+ ...deployment,+ version: versionUtils.buildUnformattedVersion({+ major: deployment.majorVersion,+ minor: deployment.minorVersion,+ }),+ }));++ return deploymentsWithUnformattedVersion;+};++export const getLatestAgentDeployment = async ({ teamId, aiAgentId }: { teamId: string; aiAgentId: string }) => {+ await aiAgentService.checkAgentExistsOrThrow(aiAgentId, teamId, {+ anonymous: false,+ });++ const deployment = await prisma.aiAgentDeployment.findFirst({+ where: {+ aiAgent: {+ id: aiAgentId,+ teamId,+ },+ },+ orderBy: {+ createdAt: 'desc',+ },+ select: {+ createdAt: true,+ id: true,+ majorVersion: true,+ minorVersion: true,+ aiAgentId: true,+ aiAgentData: true,+ aiAgentSettings: true,+ releaseNotes: true,++ aiAgent: {+ select: {+ name: true,+ },+ },+ },+ });++ if (!deployment) {+ return null;+ }++ (deployment.aiAgent as any).domain = [];++ return {+ ...deployment,+ version: versionUtils.buildUnformattedVersion({+ major: deployment.majorVersion,+ minor: deployment.minorVersion,+ }),+ };+};++export const getDeploymentByMajorMinorVersion = async (+ aiAgentId: string,+ majorVersion: string,+ minorVersion: string,+ teamId?: string,+ options?: {+ anonymous?: boolean;+ },+) => {+ const deployment = await prisma.aiAgentDeployment.findFirst({+ where: {+ aiAgentId,+ majorVersion: Number(majorVersion),+ minorVersion: Number(minorVersion),+ ...(options?.anonymous+ ? {}+ : {+ aiAgent: {+ team: {+ id: teamId as string,+ },+ },+ }),+ },++ select: {+ id: true,+ aiAgent: {+ select: {+ name: true,+ },+ },+ majorVersion: true,+ minorVersion: true,+ aiAgentId: true,+ aiAgentData: true,+ aiAgentSettings: true,+ createdAt: true,+ updatedAt: true,+ releaseNotes: true,+ },+ });++ if (!deployment) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Deployment not found');+ }++ return deployment;+};++export const fetchNextVersion = async ({ aiAgentId, tx }: { aiAgentId: string; tx?: PrismaTransaction }) => {+ const _p = tx || prisma;+ //! NEED TO BE OPTIMIZED+ // get the latest version+ const latestDeployments = await _p.aiAgentDeployment.findMany({+ where: {+ aiAgentId,+ },++ orderBy: {+ majorVersion: 'desc',+ },++ select: {+ majorVersion: true,+ minorVersion: true,+ },+ });++ const latestDeployment = latestDeployments.sort((a, b) => b.majorVersion - a.majorVersion || b.minorVersion - a.minorVersion)[0];++ if (!latestDeployment) {+ return {+ major: 1,+ minor: 0,+ };+ }++ return {+ major: latestDeployment.majorVersion,+ minor: latestDeployment.minorVersion + 1,+ };+};++export const getTeamDeploymentsCount = async (+ teamId: string,+ options?: {+ tx?: PrismaTransaction;+ },+) => {+ const _p = options?.tx || prisma;+ const count = await _p.aiAgentDeployment.count({+ where: {+ aiAgent: {+ teamId,+ },+ },+ });++ return count;+};diff --git a/packages/middleware/src/modules/ai-agent/services/deployments/strategies/AbstractDeployer.ts b/packages/middleware/src/modules/ai-agent/services/deployments/strategies/AbstractDeployer.tsnew file mode 100644index 00000000..e2c97fa2--- /dev/null+++ b/packages/middleware/src/modules/ai-agent/services/deployments/strategies/AbstractDeployer.ts@@ -0,0 +1,25 @@+import { PrismaTransaction } from '../../../../../../types';++export interface VersionComponents {+ major: number;+ minor: number;+}++export interface DeployParams {+ teamId: string;+ distribution: { url: string; name: string; id: string };+ payload: {+ releaseNotes: string;+ versionComponents: VersionComponents;+ };+ aiAgent: {+ id: string;+ settings: { key: string; value: string }[];+ snapshotData: { version: string; [key: string]: any };+ };+ tx: PrismaTransaction;+}++export abstract class AbstractDeployer {+ abstract deploy(params: DeployParams): Promise<any>;+}diff --git a/packages/middleware/src/modules/ai-agent/services/deployments/strategies/SmythOsDeployer.ts b/packages/middleware/src/modules/ai-agent/services/deployments/strategies/SmythOsDeployer.tsnew file mode 100644index 00000000..6a7278dc--- /dev/null+++ b/packages/middleware/src/modules/ai-agent/services/deployments/strategies/SmythOsDeployer.ts@@ -0,0 +1,33 @@+import { AbstractDeployer, DeployParams } from './AbstractDeployer';++export class SmythOsDeployer extends AbstractDeployer {+ async deploy(params: DeployParams) {+ // check if this agent is the first time to be deployed, if so, check QUOTA++ /**+ * Cases to reject a version:+ * - an existing existing with the same major and the minor equals to or higher than the existing record minor+ * - an existing record with a higher major+ */++ const aggregatedSettings = params.aiAgent.settings.reduce((acc, setting) => ({ ...acc, [setting.key]: setting.value }), {});++ // if no distribution id is provided, deploy on SmythOS+ const _newDeployment = await params.tx.aiAgentDeployment.create({+ data: {+ aiAgent: {+ connect: {+ id: params.aiAgent.id,+ },+ },+ majorVersion: params.payload.versionComponents.major,+ minorVersion: params.payload.versionComponents.minor,+ aiAgentData: params.aiAgent.snapshotData || {},+ aiAgentSettings: aggregatedSettings,+ releaseNotes: params.payload.releaseNotes,+ },+ });++ return _newDeployment;+ }+}diff --git a/packages/middleware/src/modules/ai-agent/services/index.ts b/packages/middleware/src/modules/ai-agent/services/index.tsnew file mode 100644index 00000000..3ba08384--- /dev/null+++ b/packages/middleware/src/modules/ai-agent/services/index.ts@@ -0,0 +1,4 @@+export * as aiAgentService from './ai-agent.service';+export * as agentDeploymentsService from './deployments/deployment.ai-agent.service';+export * as aiAgentChatsService from './chat.ai-agent.service';+export { modelAgentService } from './model-agent.service';diff --git a/packages/middleware/src/modules/ai-agent/services/model-agent.service.ts b/packages/middleware/src/modules/ai-agent/services/model-agent.service.tsnew file mode 100644index 00000000..74e8a7ec--- /dev/null+++ b/packages/middleware/src/modules/ai-agent/services/model-agent.service.ts@@ -0,0 +1,282 @@+import crypto from 'crypto';+import _ from 'lodash';+import { agentDeploymentsService } from '.';+import { prisma } from '../../../../prisma/prisma-client';+import modelAgents from '../../../data/model-agents.json';+import ApiError from '../../../utils/apiError';++/**+ * Service class for handling model agent operations+ */+class ModelAgentService {+ private readonly AGENT_PREFIX = 'model-';++ /**+ * Checks if an ID belongs to a model agent+ * @param id - The agent ID to check+ * @returns boolean indicating if ID is for a model agent+ */+ public isModelAgentId(id: string, teamId: string): boolean {+ // EXPECTED FORMAT: model-agent-${model_name}-${teamId} (model name can be anything)+ // use fastest hash logic for getting 4 (md5)+ const teamHash = this.shortenId(teamId);+ const regex = new RegExp(`^${this.AGENT_PREFIX}(.+)-${teamHash}$`);++ return regex.test(id);+ }++ public async listModelAgents(teamId: string) {+ /*+ we list model agents with the following generic logic+ - get all model files in the /model-agents folder+ - for each model file, list an skeleton agent with the following id = ${model-filename}-${teamId}+ */++ return modelAgents.map(model => {+ const id = `${model.idPrefix}-${this.shortenId(teamId)}`;+ return {+ id,+ name: model.fileData.name,+ description: model.fileData.shortDescription || model.fileData.description,+ avatar: model.settings?.find(setting => setting.key === 'avatar')?.value,+ };+ });+ }++ /**+ * Retrieves a model agent by ID with optional includes+ * @param id - The agent ID+ * @param teamId - The team ID+ * @param options - Query options including what relations to include+ */+ public async getModelAgentById(id: string, teamId: string, parentTeamId: string, options: { include: string[] }) {+ // let agent = await this.getAgent(id, teamId, options);+ let agent: any = await prisma.aiAgent.findUnique({+ where: {+ id,+ teamId,+ },+ select: this.getAgentSelect(options),+ });++ // for backward compatibility, add to the agent an empty domain object+ agent.domain = [];++ // Get template data to check if agent is up to date+ const tmpl = await this.prepareTemplateData({ id, teamId, parentTeamId });++ if (!agent) {+ // Create new agent if it doesn't exist+ console.log(`Creating new model agent. id: ${id} TeamId: ${teamId}`);+ return this.setupModelAgent(id, teamId, tmpl, options);+ }++ // Compare template data with agent data+ const changed = await this.diff(agent, tmpl);+ if (changed.data || changed.settings) {+ console.log(`Updating model agent. id: ${id} TeamId: ${teamId}`);+ agent = await this.updateAgent(id, agent, tmpl, changed, options);+ }++ const { name, updatedAt, aiAgentData, domain, lockId, lastLockBeat, lastLockSaveOperation, ...rest } = agent;+ // const isLocked = agentHasValidLock(agent.lastLockBeat, agent.lastLockSaveOperation, agent.lockId);++ return {+ name,+ updatedAt,+ data: aiAgentData?.data,+ domain: agent.domain,+ ...rest,+ };+ // return agent;+ }++ /**+ * Gets template data for an agent from Redis cache or file system+ * @param id - The agent ID+ * @returns Template data and settings+ */+ private async prepareTemplateData({ id, teamId, parentTeamId }: { id: string; teamId: string; parentTeamId: string }): Promise<TemplateData> {+ // e.g model-gpt-4o-mini-clv1cv00t0001alug52hd69j8 WE should extract gpt-4o-mini from this+ // format: model-${model_name}-${teamId}+ const tmplId = id.split('-').slice(0, -1).join('-');+ const agent = modelAgents.find(model => model.idPrefix === tmplId);+ if (!agent) {+ throw new ApiError(404, `Model agent ${tmplId} not found`);+ }++ const tmplData = agent.fileData;+ tmplData.id = id;+ tmplData.teamId = teamId;+ tmplData.parentTeamId = parentTeamId;+ (tmplData as any).debugSessionEnabled = false;+ const settings = agent.settings.map(s => ({+ ...s,+ aiAgentId: id,+ }));++ return { tmplData, settings };+ }++ private async setupModelAgent(id: string, teamId: string, data: TemplateData, options: { include: string[] }) {+ /*+ Atomically+ 1. create agent+ 2. create agent settings+ 3. create initial deployment so the user can chat with it+ */++ const agent = await prisma.$transaction(+ async tx => {+ const _agent = await tx.aiAgent.create({+ data: {+ id,+ teamId,+ name: data.tmplData?.name || 'Model',+ aiAgentData: {+ create: {+ data: data.tmplData,+ },+ },+ aiAgentSettings: {+ create: data.settings.map(s => ({+ key: s.key,+ value: s.value,+ })),+ },+ },+ select: this.getAgentSelect(options),+ });++ // for backward compatibility, add to the agent an empty domain object+ (_agent as any).domain = [];++ return _agent;+ },+ { timeout: 120_000 },+ );++ // TODO: move this into the transaction by making this service call Transactional<>+ await agentDeploymentsService.createDeployment({+ aiAgentId: agent.id,+ teamId,+ });++ return agent;+ }++ private async diff(agent, tmpl: TemplateData) {+ const settings = await prisma.aiAgentSettings.findMany({+ where: {+ aiAgentId: agent.id,+ },+ select: {+ key: true,+ value: true,+ },+ });+ const pickSettings = (obj: any) => {+ return _.pick(obj, 'key', 'value');+ };+ return {+ data: !_.isEqual(agent.aiAgentData?.data, tmpl.tmplData),+ settings: !_.isEqual(pickSettings(settings), pickSettings(tmpl.settings)),+ };+ }++ private async updateAgent(id: string, agent, tmpl: TemplateData, changed: { data: boolean; settings: boolean }, options: { include: string[] }) {+ return prisma.$transaction(+ async tx => {+ if (changed.data) {+ // await tx.aiAgentData.update({+ // where: { aiAgentId: id },+ // data: { data: tmpl.tmplData },+ // select: null,+ // });+ await tx.aiAgent.update({+ where: { id },+ data: {+ aiAgentData: {+ update: {+ data: tmpl.tmplData,+ },+ },+ name: tmpl.tmplData.name,+ },+ });+ }+ if (changed.settings) {+ for (const setting of tmpl.settings) {+ await tx.aiAgentSettings.update({+ where: { id: setting.id },+ data: { value: setting.value },+ select: null,+ });+ }+ }++ let _agent = await tx.aiAgent.findUnique({+ where: { id: agent.id },+ select: this.getAgentSelect(options),+ });++ // for backward compatibility, add to the agent an empty domain object+ (_agent as any).domain = [];++ return _agent;+ },+ { timeout: 120_000 },+ );+ }++ private getAgentSelect(options: { include: string[] }) {+ return {+ id: true,+ aiAgentData: {+ select: {+ data: true,+ },+ },+ name: true,+ updatedAt: true,+ description: true,+ ...(options.include?.includes('team.subscription')+ ? {+ team: {+ select: {+ name: true,+ id: true,+ parentId: true,+ subscription: {+ select: {+ id: true,+ properties: true,+ },+ },+ },+ },+ }+ : {}),+ _count: {+ select: {+ AiAgentDeployment: true,+ },+ },+ lastLockBeat: true,+ lastLockSaveOperation: true,+ lockId: true,+ lockedByName: true,+ };+ }++ private shortenId = (id: string, length = 8): string => {+ return crypto.createHash('md5').update(id).digest('hex').slice(0, length);+ };+}++interface TemplateData {+ tmplData: { [key: string]: any } | null;+ settings: { [key: string]: any }[] | null;+}++export const modelAgentService = new ModelAgentService();diff --git a/packages/middleware/src/modules/ai-agent/validations/ai-agent.validation.ts b/packages/middleware/src/modules/ai-agent/validations/ai-agent.validation.tsnew file mode 100644index 00000000..906e9a6c--- /dev/null+++ b/packages/middleware/src/modules/ai-agent/validations/ai-agent.validation.ts@@ -0,0 +1,356 @@+import Joi from 'joi';++export const postAiAgent = {+ body: Joi.object({+ name: Joi.string().required(),+ description: Joi.string(),+ }),+};++export const getAiAgents = {+ query: Joi.object({+ includeSettings: Joi.boolean().optional().default(false),+ contributors: Joi.boolean().optional().default(false),+ agentActivity: Joi.boolean().optional().default(false),+ page: Joi.number().optional().default(1),+ limit: Joi.number().optional().default(10),+ }),+};++export const postSaveAgent = {+ body: Joi.object({+ id: Joi.string().optional().allow(null),+ name: Joi.string().required(),+ description: Joi.string().optional().allow(null).allow(''),+ data: Joi.object().required(),+ lockId: Joi.string().optional().allow(null),+ spaceId: Joi.string().optional().allow(null),+ }),+};++export const deleteAgent = {+ params: Joi.object({+ agentId: Joi.string().required(),+ }),+};++export const requestAccess = {+ body: Joi.object({+ agentId: Joi.string().required(),+ email: Joi.string().email().required(),+ }),+};++export const getAgentById = {+ query: Joi.object({+ include: Joi.string().optional().allow(null).allow(''),+ }),+ params: Joi.object({+ agentId: Joi.string().required(),+ }),+};++// AGENT LOCKING+export const accquireAgentLock = {+ body: Joi.object({+ agentId: Joi.string().required(),+ }),+};++export const getAgentLockStatus = {+ params: Joi.object({+ agentId: Joi.string().required(),+ }),+};++export const releaseAgentLock = {+ body: Joi.object({+ agentId: Joi.string().required(),+ lockId: Joi.string().required(),+ }),+};++export const sendAgentLockBeat = {+ body: Joi.object({+ agentId: Joi.string().required(),+ lockId: Joi.string().required(),+ }),+};++// AI AGENT STATE++export const createState = {+ body: Joi.object({+ key: Joi.string().required(),+ value: Joi.string().required(),+ }),+};++export const getState = {+ params: Joi.object({+ key: Joi.string().required(),+ agentId: Joi.string().required(),+ }),+};++export const deleteState = {+ params: Joi.object({+ key: Joi.string().required(),+ agentId: Joi.string().required(),+ }),+};++// AI AGENT SETTINGS++export const createAgentSetting = {+ body: Joi.object({+ key: Joi.string().required(),+ value: Joi.string().required(),+ }),+};++export const getAgentByDomain = {+ query: Joi.object({+ domainName: Joi.string().required(),+ method: Joi.any().optional(), // SHOULD BE REMOVED (BACKWARD COMPATIBILITY)+ endpointPath: Joi.any().optional(), // SHOULD BE REMOVED (BACKWARD COMPATIBILITY)+ }),+};++export const postDeployment = {+ body: Joi.object({+ // version regex should match: "1.0", "1.23"++ version: Joi.string()+ .regex(/^\d+\.\d+$/)+ .optional()+ .allow(null),++ releaseNotes: Joi.string().optional().allow(null),+ agentId: Joi.string().required(),+ }),+};++export const getDeployment = {+ params: Joi.object({+ deploymentId: Joi.string().required(),+ }),+};++export const getLatestDeployment = {+ params: Joi.object({+ agentId: Joi.string().required(),+ }),+};++export const getDeploymentsByAgentId = {+ params: Joi.object({+ agentId: Joi.string().required(),+ }),++ query: Joi.object({+ include: Joi.string().optional().allow(null).allow(''),+ }),+};++export const getDeploymentByMajorMinorVersion = {+ params: Joi.object({+ agentId: Joi.string().required(),+ majorVersion: Joi.number().required(),+ minorVersion: Joi.number().required(),+ }),+};++export const createBulkCall = {+ params: Joi.object({+ agentId: Joi.string().required(),+ }),+ body: Joi.object({+ rows: Joi.array().items(Joi.object()).min(1).max(4000).required(),++ componentId: Joi.string().required(),+ }),+ options: Joi.object({+ delay: Joi.number().optional().allow(null),+ }).optional(),+};++export const callSkill = {+ params: Joi.object({+ agentId: Joi.string().required(),+ }),++ body: Joi.object({+ componentId: Joi.string().required(),+ payload: Joi.object().optional().allow(null).allow(''),+ // only allow dev and prod, and a reg expression for matching vX.X+ version: Joi.string()+ .optional()+ .allow('dev', 'latest')+ .regex(/^v\d+\.\d+$/),+ }),+};++export const getBulkCallInfo = {+ params: Joi.object({+ agentId: Joi.string().required(),+ }),++ query: Joi.object({+ componentId: Joi.string().required(),+ }),+};+export const getLatestBulkCallInfo = {+ params: Joi.object({+ agentId: Joi.string().required(),+ }),++ query: Joi.object({+ componentId: Joi.string().required(),+ }),+};++export const stopBulkCall = {+ params: Joi.object({+ agentId: Joi.string().required(),+ }),++ query: Joi.object({+ componentId: Joi.string().required(),+ }),+};++export const getAgentByIdM2M = {+ query: Joi.object({+ include: Joi.string().optional().allow(null).allow(''),+ }),+ params: Joi.object({+ agentId: Joi.string().required(),+ }),+};++export const getConversationByIdM2M = {+ params: Joi.object({+ conversationId: Joi.string().required(),+ }),+};++export const getConversationsM2M = {+ query: Joi.object({+ ownerId: Joi.number().optional(),+ agentId: Joi.string().optional(),+ }),+};++// export const getConversationByAgentIdM2M = {+// params: Joi.object({+// agentId: Joi.string().required(),+// }),+// };++export const createConversationM2M = {+ body: Joi.object({+ conversation: Joi.object({+ label: Joi.string().optional().allow(null).allow(''),+ summary: Joi.string().optional().allow(null).allow(''),+ teamId: Joi.string().required(),+ ownerId: Joi.number().optional(),+ aiAgentId: Joi.string().required(),+ chunkSize: Joi.number().optional().allow(null),+ lastChunkID: Joi.string().optional().allow(null),+ }),+ }),+};++export const updateConversationM2M = {+ params: Joi.object({+ conversationId: Joi.string().required(),+ }),+ body: Joi.object({+ conversation: Joi.object({+ ownerId: Joi.number().optional().allow(null),+ chunkSize: Joi.number().optional().allow(null),+ lastChunkID: Joi.string().optional().allow(null),+ label: Joi.string().optional().allow(null),+ summary: Joi.string().optional().allow(null),+ }),+ }),+};++export const deleteConversationM2M = {+ params: Joi.object({+ conversationId: Joi.string().required(),+ }),+};++export const deleteConversationsByAgentIdM2M = {+ params: Joi.object({+ agentId: Joi.string().required(),+ }),+};++export const getTeamConversations = {+ query: Joi.object({+ isOwner: Joi.boolean().optional().default(false),++ page: Joi.number().optional().default(1),+ limit: Joi.number().optional().default(10),++ order: Joi.string().optional().default('desc'),+ sortField: Joi.string().optional().default('createdAt'),+ }),+};+export const getMyConversations = {+ query: Joi.object({+ page: Joi.number().optional().default(1),+ limit: Joi.number().optional().default(10),+ }),+};++export const createTeamConversation = {+ body: Joi.object({+ conversation: Joi.object({+ label: Joi.string().optional().allow(null).allow(''),+ summary: Joi.string().optional().allow(null).allow(''),+ aiAgentId: Joi.string().required(),+ chunkSize: Joi.number().optional().allow(null),+ lastChunkID: Joi.string().optional().allow(null),+ }),+ }),+};++export const updateTeamConversation = {+ params: Joi.object({+ conversationId: Joi.string().required(),+ }),+ body: Joi.object({+ conversation: Joi.object({+ label: Joi.string().optional().allow(null),+ summary: Joi.string().optional().allow(null),+ }),+ }),+};++export const getTeamConversationById = {+ params: Joi.object({+ conversationId: Joi.string().required(),+ }),+};++export const deleteTeamConversation = {+ params: Joi.object({+ conversationId: Joi.string().required(),+ }),+};++export const getTeamAgents = {+ params: Joi.object().keys({+ teamId: Joi.string().required(),+ }),+ query: Joi.object().keys({+ deployedOnly: Joi.boolean().default(false),+ includeData: Joi.boolean().default(false),+ page: Joi.number().min(1),+ limit: Joi.number().min(1),+ }),+};diff --git a/packages/middleware/src/modules/auth/helpers/auth-express.helper.ts b/packages/middleware/src/modules/auth/helpers/auth-express.helper.tsnew file mode 100644index 00000000..86cb91e5--- /dev/null+++ b/packages/middleware/src/modules/auth/helpers/auth-express.helper.ts@@ -0,0 +1,47 @@+import { Response } from 'express';+import ApiError from '../../../utils/apiError';+import { LogtoUser } from '../../../../types';++export const authExpressHelpers = {+ getUserId: (res: Response) => {+ const userId = res.locals.user.id;+ if (!userId) throw new ApiError(500, 'User id not found');+ return userId;+ },++ getUser: (res: Response) => {+ const user = res.locals.user;+ if (!user) throw new ApiError(500, 'User not found');+ return user;+ },++ _getLogtoUser: (res: Response): LogtoUser => {+ const user = res.locals.logtoUser;+ if (!user) throw new ApiError(500, 'User not found');+ return user;+ },++ getUserEmail: (res: Response): string => {+ const email = res.locals.user.email;+ if (!email) throw new ApiError(500, 'Email not found');+ return email;+ },++ getTeamId: (res: Response) => {+ const teamId = res.locals.targetTeamId || res.locals.user.teamId; // fallback to user's team id+ if (!teamId) throw new ApiError(500, 'Target team id not found');+ return teamId;+ },++ // getChosenTeamId: (res: Response) => {+ // const teamId = res.locals.targetTeamId || res.locals.user.teamId; // fallback to user's team id+ // if (!teamId) throw new ApiError(500, 'Target team id not found');+ // return teamId;+ // },++ getParentTeamId: (res: Response) => {+ const teamId = res.locals.user.teamId;+ if (!teamId) throw new ApiError(500, 'Team id not found');+ return teamId;+ },+};diff --git a/packages/middleware/src/modules/auth/middlewares/auth.middleware/index.ts b/packages/middleware/src/modules/auth/middlewares/auth.middleware/index.tsnew file mode 100644index 00000000..d99fdda1--- /dev/null+++ b/packages/middleware/src/modules/auth/middlewares/auth.middleware/index.ts@@ -0,0 +1,87 @@+/* eslint-disable no-else-return */+/* eslint-disable consistent-return */+import { NextFunction } from 'express';+import httpStatus from 'http-status';+import { LOGGER } from '../../../../../config/logging';+import ApiError from '../../../../utils/apiError';+import { teamService } from '../../../team/services';+import tokenVerStrategies from './strategies';++const authMiddlewareFactory = ({ requireTeam = true, allowM2M = false, limitToM2M = false }) => {+ return async (req: any, res: any, next: NextFunction) => {+ try {+ const token: string = req.headers.authorization?.split(' ')[1] || req.query.token;+ const isM2MToken = token.includes('M2M_TOKEN');+ const isUIAuthToken = token.includes('UI_AUTH_TOKEN');++ if (isM2MToken) {+ // LOGGER.info(`M2M auth for token in progress....`);+ if (!allowM2M) throw new ApiError(httpStatus.FORBIDDEN, 'M2M is not enabled'); // we only use JWT for M2M++ const { success } = await tokenVerStrategies.defaultM2MAuth.verifyToken(token);++ if (!success) {+ // return res.status(401).json({ error: 'Access token is invalid or expired' });+ return next(new ApiError(httpStatus.UNAUTHORIZED, 'Access token is invalid or expired'));+ }+ res.locals.isM2M = true;++ return next();+ } else if (isUIAuthToken) {+ // LOGGER.info(`User ui token auth for token in progress....`);+ // user token auth+ if (limitToM2M) throw new ApiError(httpStatus.FORBIDDEN, 'User auth is not enabled for this request');++ const { data, success } = await tokenVerStrategies.defaultUIAuth.verifyToken(token);++ if (!success) {+ // return res.status(401).json({ error: 'Access token is invalid or expired' });+ return next(new ApiError(httpStatus.UNAUTHORIZED, 'Access token is invalid or expired'));+ }++ res.locals.logtoUser = data!.logtoUser;+ res.locals.user = data!.user;+ res.locals.userId = data!.userId;++ // check if another teamid was passed in the request header. if so, make sure that the user is part of that team and set the teamId in res.locals (res.locals.user.teamId)+ const teamIdHeader = req.headers['x-smyth-team-id'];+ if (teamIdHeader) {+ // check if the user is part of the team+ const hasTeamAccess = await teamService.isUserPartOfTeam(data!.userId, teamIdHeader);++ if (!hasTeamAccess) {+ throw new ApiError(httpStatus.FORBIDDEN, 'You do not have access to this team');+ }++ res.locals.targetTeamId = teamIdHeader;+ }++ if (requireTeam && !data!.user?.teamId) {+ throw new ApiError(httpStatus.BAD_REQUEST, 'Please create a team and try again');+ }++ runLocalsFieldsSanityChecks(res);++ return next();+ }+ } catch (error: any) {+ // res.status(500).json({ error: error.message });+ return next(new ApiError(error.statusCode || httpStatus.INTERNAL_SERVER_ERROR, error.message));+ }+ };+};++const runLocalsFieldsSanityChecks = (res: any) => {+ if (!res.locals.logtoUser || !res.locals.user || !res.locals.userId) {+ LOGGER.error(new Error(`User auth middleware failed to set required fields in res.locals`));+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, 'Something went wrong');+ }+};++const userAuthMiddleware = authMiddlewareFactory({+ allowM2M: false,+ requireTeam: true,+ limitToM2M: false,+});++export { authMiddlewareFactory, userAuthMiddleware };diff --git a/packages/middleware/src/modules/auth/middlewares/auth.middleware/strategies/defaultM2MAuth.verification.ts b/packages/middleware/src/modules/auth/middlewares/auth.middleware/strategies/defaultM2MAuth.verification.tsnew file mode 100644index 00000000..8f23cd42--- /dev/null+++ b/packages/middleware/src/modules/auth/middlewares/auth.middleware/strategies/defaultM2MAuth.verification.ts@@ -0,0 +1,16 @@+/* eslint-disable no-await-in-loop */+import { AuthStrategy } from '.';+import { LOGGER } from '../../../../../../config/logging';++export default class DefaultM2MAuth implements AuthStrategy {+ name = 'defaultM2MAuth';++ async verifyToken(token: string) {+ if (!token) {+ LOGGER.error(new Error('M2M JWT verification failed: No M2M token found in request header'));+ return { error: 'Access token is required', success: false };+ }++ return { error: undefined, data: {}, success: true };+ }+}diff --git a/packages/middleware/src/modules/auth/middlewares/auth.middleware/strategies/defaultUIAuth.verification.ts b/packages/middleware/src/modules/auth/middlewares/auth.middleware/strategies/defaultUIAuth.verification.tsnew file mode 100644index 00000000..c52156b1--- /dev/null+++ b/packages/middleware/src/modules/auth/middlewares/auth.middleware/strategies/defaultUIAuth.verification.ts@@ -0,0 +1,64 @@+/* eslint-disable no-else-return */+import { AuthStrategy } from '.';+import { LOGGER } from '../../../../../../config/logging';+import { userService } from '../../../../user/services';++interface UserTokenData {+ logtoUser?: any;+ user?: {+ id: any;+ email: any;+ teamId: any;+ };+ userId?: any;+}++export default class DefaultUIAuth implements AuthStrategy {+ name = 'defaultUIAuth';++ async verifyToken(token: string) {+ const data: UserTokenData = {};++ if (!token) {+ return { error: 'Access token is required', data: null, success: false };+ }++ const userAuth = {+ sub: 'sub_1',+ name: 'Admin',+ picture: undefined,+ updated_at: Date.now(),+ username: null,+ created_at: Date.now(),+ email: '[email protected]',+ email_verified: true,+ primaryEmail: '[email protected]',+ avatar: undefined,+ };+ data.logtoUser = userAuth;+ const logtoUser = data.logtoUser;++ if (!logtoUser.primaryEmail) logtoUser.primaryEmail = logtoUser.email;+ if (!logtoUser.avatar) logtoUser.avatar = logtoUser.picture;+ // LOGGER.info(`User ${logtoUser.primaryEmail} is logging in (name: ${logtoUser.name})`);+ const user = await userService.findOrCreateUser({+ email: logtoUser.primaryEmail,+ name: logtoUser.name,+ avatar: logtoUser.avatar,+ }); //* check if user exists in our DB, if not, create one++ if (!user.teamId) {+ LOGGER.info(`User ${logtoUser.primaryEmail} is logging without a team`);+ return { error: 'User does not belong to a team', data: null, success: false };+ }++ data.user = {+ id: user.id,+ email: user.email,+ teamId: user.teamId,+ };+ data.userId = user.id;++ return { data, success: true };+ }+}diff --git a/packages/middleware/src/modules/auth/middlewares/auth.middleware/strategies/index.ts b/packages/middleware/src/modules/auth/middlewares/auth.middleware/strategies/index.tsnew file mode 100644index 00000000..50bd4053--- /dev/null+++ b/packages/middleware/src/modules/auth/middlewares/auth.middleware/strategies/index.ts@@ -0,0 +1,18 @@+import DefaultM2MAuth from './defaultM2MAuth.verification';+import DefaultUIAuth from './defaultUIAuth.verification';++export interface AuthStrategy {+ name: string;+ verifyToken: (token: string) => Promise<{+ error?: string | null;+ data?: any | null;+ success: boolean;+ }>;+}++const tokenVerStrategies = {+ defaultUIAuth: new DefaultUIAuth(),+ defaultM2MAuth: new DefaultM2MAuth(),+};++export default tokenVerStrategies;diff --git a/packages/middleware/src/modules/domains/controllers/_sysapi/domain-registeration.controller.ts b/packages/middleware/src/modules/domains/controllers/_sysapi/domain-registeration.controller.tsnew file mode 100644index 00000000..6e840808--- /dev/null+++ b/packages/middleware/src/modules/domains/controllers/_sysapi/domain-registeration.controller.ts@@ -0,0 +1,31 @@+import httpStatus from 'http-status';+import { ExpressHandler } from '../../../../../types';+import { domainRegisterationService } from '../../services';++export const queryDomain: ExpressHandler<{ name: string }, { domain: any }> = async (req, res) => {+ const { name } = req.body;++ const domain = await domainRegisterationService.getDomain(name, undefined, {+ anonymous: true,+ });++ res.status(httpStatus.OK).json({+ message: 'Domain retrieved successfully',+ domain,+ });+};++export const getDomains: ExpressHandler<null, { domains: any }> = async (req, res) => {+ const { verified = true, name, aiAgentId } = req.query;++ const domains = await domainRegisterationService.getDomainsM2M({+ verified: Boolean(verified),+ name: name as string,+ aiAgentId: aiAgentId as string,+ });++ res.status(httpStatus.OK).json({+ message: 'Domains retrieved successfully',+ domains,+ });+};diff --git a/packages/middleware/src/modules/domains/controllers/domain-registeration.controller.ts b/packages/middleware/src/modules/domains/controllers/domain-registeration.controller.tsnew file mode 100644index 00000000..ef728615--- /dev/null+++ b/packages/middleware/src/modules/domains/controllers/domain-registeration.controller.ts@@ -0,0 +1,75 @@+import httpStatus from 'http-status';+import { ExpressHandler } from '../../../../types';+import { authExpressHelpers } from '../../auth/helpers/auth-express.helper';+import { domainRegisterationService } from '../services';++//* DOMAINS++export const postDomain: ExpressHandler<{ name: string }, { domain: any }> = async (req, res) => {+ const { name } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);++ const domain = await domainRegisterationService.createDomain(name, teamId);++ res.status(httpStatus.OK).json({+ message: 'Domain saved successfully',+ domain,+ });+};++export const putUpdateDomain: ExpressHandler<+ {+ name: string;+ data: {+ aiAgentId: string | null;+ };+ },+ {}+> = async (req, res) => {+ const { name, data } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);++ await domainRegisterationService.updateDomain(name, teamId, data);++ res.status(httpStatus.OK).json({+ message: 'Domain updated successfully',+ });+};++export const getDomains: ExpressHandler<null, { domains: any }> = async (req, res) => {+ const { verified = false } = req.query;++ const domains = await domainRegisterationService.getDomains(authExpressHelpers.getTeamId(res), {+ verified: verified === 'true',+ });++ res.status(httpStatus.OK).json({+ message: 'Domains retrieved successfully',+ domains,+ });+};++export const queryDomain: ExpressHandler<{ name: string }, { domain: any }> = async (req, res) => {+ const { name } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);++ const domain = await domainRegisterationService.getDomain(name, teamId, {+ anonymous: false,+ });++ res.status(httpStatus.OK).json({+ message: 'Domain retrieved successfully',+ domain,+ });+};++export const deleteDomain: ExpressHandler<{ name: string }, {}> = async (req, res) => {+ const { name } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);++ await domainRegisterationService.deleteDomain(name, teamId);++ res.status(httpStatus.OK).json({+ message: 'Domain deleted successfully',+ });+};diff --git a/packages/middleware/src/modules/domains/routes/_sysapi/domain-registeration.route.ts b/packages/middleware/src/modules/domains/routes/_sysapi/domain-registeration.route.tsnew file mode 100644index 00000000..042b74c0--- /dev/null+++ b/packages/middleware/src/modules/domains/routes/_sysapi/domain-registeration.route.ts@@ -0,0 +1,14 @@+import { Router } from 'express';+import asyncHandler from 'express-async-handler';++import * as domainController from '../../controllers/_sysapi/domain-registeration.controller';+import { validate } from '../../../../middlewares/validate.middleware';+import * as domainValidations from '../../validations/domain-registeration.validation';++const router = Router();++router.post('/domain/query', validate(domainValidations.queryDomain), asyncHandler(domainController.queryDomain));++router.get('/domains', validate(domainValidations.getDomainsM2M), asyncHandler(domainController.getDomains));++export { router as _domainRouter };diff --git a/packages/middleware/src/modules/domains/routes/domain-registeration.route.ts b/packages/middleware/src/modules/domains/routes/domain-registeration.route.tsnew file mode 100644index 00000000..2f449d05--- /dev/null+++ b/packages/middleware/src/modules/domains/routes/domain-registeration.route.ts@@ -0,0 +1,26 @@+import { Router } from 'express';+import asyncHandler from 'express-async-handler';++import { validate } from '../../../middlewares/validate.middleware';+import { authMiddlewareFactory, userAuthMiddleware } from '../../auth/middlewares/auth.middleware';+import * as domainController from '../controllers/domain-registeration.controller';+import * as domainValidations from '../validations/domain-registeration.validation';++const router = Router();++router.post('/domain', userAuthMiddleware, validate(domainValidations.postDomain), asyncHandler(domainController.postDomain));++router.put('/domain', userAuthMiddleware, validate(domainValidations.putUpdateDomain), asyncHandler(domainController.putUpdateDomain));+router.get('/domains', userAuthMiddleware, asyncHandler(domainController.getDomains));++router.post(+ '/domain/query',+ authMiddlewareFactory({+ allowM2M: true,+ }),+ validate(domainValidations.queryDomain),+ asyncHandler(domainController.queryDomain),+);+router.post('/domain/delete', userAuthMiddleware, validate(domainValidations.deleteDomain), asyncHandler(domainController.deleteDomain));++export { router as domainRouter };diff --git a/packages/middleware/src/modules/domains/services/domain-registeration.service.ts b/packages/middleware/src/modules/domains/services/domain-registeration.service.tsnew file mode 100644index 00000000..9604e8dc--- /dev/null+++ b/packages/middleware/src/modules/domains/services/domain-registeration.service.ts@@ -0,0 +1,66 @@+import httpStatus from 'http-status';+import { PrismaTransaction } from '../../../../types';+import ApiError from '../../../utils/apiError';++export const getDomains = async (+ teamId: string | undefined,+ options: {+ verified: boolean;+ },+) => {+ return [];+};++export const getDomainsM2M = async (query?: { verified?: boolean; name?: string; aiAgentId?: string }) => {+ return [];+};++export const getDomain = async (+ domainName: string,+ teamId: string | undefined,+ options: {+ anonymous: boolean;+ },+) => {+ throw new ApiError(httpStatus.NOT_FOUND, 'Domain not found');+};++export const createDomain = async (name: string, teamId: string) => {+ return Promise.resolve(true);+};++export const updateDomain = async (+ domainName: string,+ teamId: string,+ data: {+ aiAgentId?: string | null;+ },+): Promise<any> => {+ return Promise.resolve(true);+};++export const verifyDomain = async (name: string, teamId: string) => {+ return Promise.resolve(true);+};++export const checkDomainStatus = async (name: string, teamId: string) => {+ return {+ status: false,+ teamId: teamId,+ aiAgentId: null,+ };+};++export const deleteDomain = async (domainName: string, teamId: string) => {+ return Promise.resolve(true);+};++export const checkDomainNameExists = async (+ name: string,+ teamId: string,+ options?: {+ tx: PrismaTransaction;+ },+) => {+ return Promise.resolve(true);+};diff --git a/packages/middleware/src/modules/domains/services/index.ts b/packages/middleware/src/modules/domains/services/index.tsnew file mode 100644index 00000000..76056828--- /dev/null+++ b/packages/middleware/src/modules/domains/services/index.ts@@ -0,0 +1 @@+export * as domainRegisterationService from './domain-registeration.service';diff --git a/packages/middleware/src/modules/domains/validations/domain-registeration.validation.ts b/packages/middleware/src/modules/domains/validations/domain-registeration.validation.tsnew file mode 100644index 00000000..ce51c8a0--- /dev/null+++ b/packages/middleware/src/modules/domains/validations/domain-registeration.validation.ts@@ -0,0 +1,64 @@+import Joi from 'joi';++export const postDomain = {+ body: Joi.object({+ name: Joi.string().required(),+ }),+};++export const putUpdateDomain = {+ body: Joi.object({+ name: Joi.string().required(),+ data: Joi.object({+ aiAgentId: Joi.string().required().optional().allow(null).allow(''),+ }),+ }),+};++export const queryDomain = {+ body: Joi.object({+ name: Joi.string().required(),+ }),+};+export const deleteDomain = {+ body: Joi.object({+ name: Joi.string().required(),+ }),+};++export const queryEndpoint = {+ body: Joi.object({+ path: Joi.string().required(),+ domainName: Joi.string().required(),+ method: Joi.string().required().valid('GET', 'POST', 'PUT', 'DELETE'),+ }),+};++export const deleteEndpoint = {+ body: Joi.object({+ path: Joi.string().required(),+ domainName: Joi.string().required(),+ // methods allowed: GET, POST, PUT, DELETE+ method: Joi.string().required().valid('GET', 'POST', 'PUT', 'DELETE'),+ }),+};++export const postEndpoint = {+ body: Joi.object({+ path: Joi.string().required(),+ data: Joi.object({+ method: Joi.string().required().valid('GET', 'POST', 'PUT', 'DELETE'),+ componentId: Joi.any().required(),+ }).required(),+ agentId: Joi.string().required(),+ domainName: Joi.string().required(),+ }),+};++export const getDomainsM2M = {+ query: Joi.object({+ verified: Joi.boolean().optional(),+ name: Joi.string().optional().allow(null).allow(''),+ aiAgentId: Joi.string().optional().allow(null).allow(''),+ }),+};diff --git a/packages/middleware/src/modules/embodiment/controllers/_sysapi/embodiment.controller.ts b/packages/middleware/src/modules/embodiment/controllers/_sysapi/embodiment.controller.tsnew file mode 100644index 00000000..369f4f4a--- /dev/null+++ b/packages/middleware/src/modules/embodiment/controllers/_sysapi/embodiment.controller.ts@@ -0,0 +1,16 @@+import { ExpressHandlerWithParams } from '../../../../../types';+import { embodimentService } from '../../services';+import httpStatus from 'http-status';++export const getEmbodimentsByAgentId: ExpressHandlerWithParams<{}, {}, { embodiments: any }> = async (req, res) => {+ const { aiAgentId } = req.query;++ const embodiments = await embodimentService.getEmbodiments(aiAgentId, undefined, {+ anonymous: true,+ });++ res.status(httpStatus.OK).json({+ message: 'Embodiments retrieved successfully',+ embodiments,+ });+};diff --git a/packages/middleware/src/modules/embodiment/controllers/embodiment.controller.ts b/packages/middleware/src/modules/embodiment/controllers/embodiment.controller.tsnew file mode 100644index 00000000..c4b30432--- /dev/null+++ b/packages/middleware/src/modules/embodiment/controllers/embodiment.controller.ts@@ -0,0 +1,95 @@+import httpStatus from 'http-status';+import { ExpressHandler } from '../../../../types';+import { embodimentService } from '../services';+import { aiAgentService } from '../../ai-agent/services';+import { authExpressHelpers } from '../../auth/helpers/auth-express.helper';++export const createEmbodiment: ExpressHandler<+ {+ type: string;+ properties: object;+ aiAgentId: string;+ },+ { embodiment: any }+> = async (req, res) => {+ const { aiAgentId, type, properties } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);++ const embodiment = await embodimentService.createEmbodiment({+ teamId,+ type,+ properties,+ aiAgentId,+ });++ return res.status(httpStatus.CREATED).json({ embodiment });+};++export const getEmbodiments: ExpressHandler<{}, { embodiments: any }> = async (req, res) => {+ const aiAgentId = req.query.aiAgentId as string;+ const teamId = authExpressHelpers.getTeamId(res);++ const embodiments = await embodimentService.getEmbodiments(aiAgentId, teamId);++ return res.status(httpStatus.OK).json({+ message: 'Embodiments retrieved successfully',+ embodiments,+ });+};++export const getEmbodiment: ExpressHandler<+ {+ embodimentId: string;+ },+ { embodiment: any }+> = async (req, res) => {+ const { embodimentId } = req.params;+ const teamId = authExpressHelpers.getTeamId(res);++ const embodiment = await embodimentService.getEmbodiment(+embodimentId, teamId);++ return res.status(httpStatus.OK).json({+ message: 'Embodiment retrieved successfully',+ embodiment,+ });+};++export const updateEmbodiment: ExpressHandler<+ {+ embodimentId: string;+ type: string;+ properties: object;+ },+ { embodiment: any }+> = async (req, res) => {+ const { embodimentId, type, properties } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);++ const embodiment = await embodimentService.updateEmbodiment({+ embodimentId: +embodimentId,+ type,+ properties,+ teamId,+ });++ return res.status(httpStatus.OK).json({+ message: 'Embodiment updated successfully',+ embodiment,+ });+};++export const deleteEmbodiment: ExpressHandler<+ {+ embodimentId: string;+ },+ {}+> = async (req, res) => {+ const { embodimentId } = req.params;+ const teamId = authExpressHelpers.getTeamId(res);++ await embodimentService.deleteEmbodiment(+embodimentId, teamId);++ return res.status(httpStatus.OK).json({+ message: 'Embodiment deleted successfully',+ });+};diff --git a/packages/middleware/src/modules/embodiment/routes/_sysapi/index.ts b/packages/middleware/src/modules/embodiment/routes/_sysapi/index.tsnew file mode 100644index 00000000..ceebc7a0--- /dev/null+++ b/packages/middleware/src/modules/embodiment/routes/_sysapi/index.ts@@ -0,0 +1,12 @@+import { Router } from 'express';+import asyncHandler from 'express-async-handler';++import * as embodimentController from '../../controllers/_sysapi/embodiment.controller';+import { validate } from '../../../../middlewares/validate.middleware';+import * as embodimentValidations from '../../validations/embodiment.validation';++const router = Router();++router.get('/embodiments', validate(embodimentValidations.getEmbodimentsByAgentId), asyncHandler(embodimentController.getEmbodimentsByAgentId));++export { router as _embodimentRouter };diff --git a/packages/middleware/src/modules/embodiment/routes/index.ts b/packages/middleware/src/modules/embodiment/routes/index.tsnew file mode 100644index 00000000..36c51147--- /dev/null+++ b/packages/middleware/src/modules/embodiment/routes/index.ts@@ -0,0 +1,41 @@+import { Router } from 'express';+import asyncHandler from 'express-async-handler';+import * as embodimentValidations from '../validations/embodiment.validation';+import { validate } from '../../../middlewares/validate.middleware';+import * as embodimentController from '../controllers/embodiment.controller';+import { userAuthMiddleware } from '../../auth/middlewares/auth.middleware';++const router = Router();++router.post(+ '/embodiments',+ [userAuthMiddleware, validate(embodimentValidations.postEmbodiment)],+ asyncHandler(embodimentController.createEmbodiment),+);++router.get(+ '/embodiments',+ [userAuthMiddleware],+ validate(embodimentValidations.getEmbodimentsByAgentId),+ asyncHandler(embodimentController.getEmbodiments),+);++router.get(+ '/embodiments/:embodimentId',+ [userAuthMiddleware, validate(embodimentValidations.getEmbodiment)],+ asyncHandler(embodimentController.getEmbodiment),+);++router.put(+ '/embodiments',+ [userAuthMiddleware, validate(embodimentValidations.updateEmbodiment)],+ asyncHandler(embodimentController.updateEmbodiment),+);++router.delete(+ '/embodiments/:embodimentId',+ [userAuthMiddleware, validate(embodimentValidations.deleteEmbodiment)],+ asyncHandler(embodimentController.deleteEmbodiment),+);++export { router as embodimentRouter };diff --git a/packages/middleware/src/modules/embodiment/services/embodiment.service.ts b/packages/middleware/src/modules/embodiment/services/embodiment.service.tsnew file mode 100644index 00000000..1ff8a13e--- /dev/null+++ b/packages/middleware/src/modules/embodiment/services/embodiment.service.ts@@ -0,0 +1,170 @@+import httpStatus from 'http-status';+import ApiError from '../../../utils/apiError';+import { prisma } from '../../../../prisma/prisma-client';+import { aiAgentService } from '../../ai-agent/services';+import { PrismaTransaction } from '../../../../types';++export const checkEmbodimentExistsOrThrow = async (+ embodimentId: number,+ teamId: string,+ options?: {+ tx?: PrismaTransaction;+ },+) => {+ const _p = options?.tx || prisma;++ const embodiment = await _p.embodiment.findFirst({+ where: {+ id: embodimentId,+ aiAgent: {+ teamId,+ },+ },+ select: {+ id: true,+ },+ });++ if (!embodiment) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Embodiment not found');+ }+};++export const createEmbodiment = async ({+ type,+ properties,+ aiAgentId,+ teamId,+}: {+ type: string;+ properties: object;+ aiAgentId: string;+ teamId: string;+}) => {+ const embodiment = await prisma.$transaction(async tx => {+ await aiAgentService.checkAgentExistsOrThrow(aiAgentId, teamId, {+ tx,+ });++ const _newRecord = await tx.embodiment.create({+ data: {+ type,+ properties,+ aiAgent: {+ connect: {+ id: aiAgentId,+ },+ },+ },+ select: {+ createdAt: true,+ id: true,+ type: true,+ properties: true,+ aiAgentId: true,+ },+ });++ return _newRecord;+ });+ return embodiment;+};++export const getEmbodiments = async (+ aiAgentId: string,+ teamId: string | undefined,+ options?: {+ anonymous: boolean;+ },+) => {+ await aiAgentService.checkAgentExistsOrThrow(aiAgentId, teamId, {+ anonymous: options?.anonymous,+ });++ const embodiments = await prisma.embodiment.findMany({+ where: {+ aiAgent: {+ ...(options?.anonymous ? {} : { teamId }),+ id: aiAgentId,+ },+ },+ select: {+ createdAt: true,+ id: true,+ type: true,+ properties: true,+ aiAgentId: true,+ },+ });+ return embodiments;+};++export const getEmbodiment = async (embodimentId: number, teamId: string) => {+ const embodiment = await prisma.embodiment.findFirst({+ where: {+ id: embodimentId,+ aiAgent: {+ teamId,+ },+ },+ select: {+ createdAt: true,+ id: true,+ type: true,+ properties: true,+ aiAgentId: true,+ },+ });++ if (!embodiment) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Embodiment not found');+ }++ return embodiment;+};++export const updateEmbodiment = async ({+ embodimentId,+ type,+ properties,+ teamId,+}: {+ embodimentId: number;+ type: string;+ properties: object;+ teamId: string;+}) => {+ await prisma.$transaction(async tx => {+ await checkEmbodimentExistsOrThrow(embodimentId, teamId, { tx });++ await tx.embodiment.updateMany({+ where: {+ id: embodimentId,+ aiAgent: {+ teamId,+ },+ },+ data: {+ type,+ properties,+ },+ });+ });+};++export const deleteEmbodiment = async (embodimentId: number, teamId: string) => {+ await prisma.$transaction(async tx => {+ const deleted = await tx.embodiment.deleteMany({+ where: {+ id: embodimentId,+ aiAgent: {+ teamId,+ },+ },+ });++ if (deleted.count === 0) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Embodiment not found');+ }+ });+};diff --git a/packages/middleware/src/modules/embodiment/services/index.ts b/packages/middleware/src/modules/embodiment/services/index.tsnew file mode 100644index 00000000..5ba00a2c--- /dev/null+++ b/packages/middleware/src/modules/embodiment/services/index.ts@@ -0,0 +1 @@+export * as embodimentService from './embodiment.service';diff --git a/packages/middleware/src/modules/embodiment/validations/embodiment.validation.ts b/packages/middleware/src/modules/embodiment/validations/embodiment.validation.tsnew file mode 100644index 00000000..af803ede--- /dev/null+++ b/packages/middleware/src/modules/embodiment/validations/embodiment.validation.ts@@ -0,0 +1,34 @@+import Joi from 'joi';++export const postEmbodiment = {+ body: Joi.object({+ type: Joi.string().required(),+ properties: Joi.object().required(),+ aiAgentId: Joi.string().required(),+ }),+};++export const getEmbodiment = {+ params: Joi.object({+ embodimentId: Joi.number().required(),+ }),+};+export const getEmbodimentsByAgentId = {+ query: Joi.object({+ aiAgentId: Joi.string().required(),+ }),+};++export const updateEmbodiment = {+ body: Joi.object({+ type: Joi.string().required(),+ properties: Joi.object().required(),+ embodimentId: Joi.number().required(),+ }),+};++export const deleteEmbodiment = {+ params: Joi.object({+ embodimentId: Joi.number().required(),+ }),+};diff --git a/packages/middleware/src/modules/quota/interfaces.ts b/packages/middleware/src/modules/quota/interfaces.tsnew file mode 100644index 00000000..3af9d76e--- /dev/null+++ b/packages/middleware/src/modules/quota/interfaces.ts@@ -0,0 +1,34 @@+export interface PlanProperties {+ limits?: PlanPropLimits;+ flags?: PlanPropFlags;+ app_version?: string;++ [key: string]: any;+}++export interface PlanPropLimits {+ prodAiAgents?: number | null;+ devAiAgents?: number | null;+ teamMembers?: number | null;+ spaces?: number | null;+ dataPoolUsageGB?: number | null;+}++export interface PlanPropFlags {+ embodimentsEnabled?: boolean;+ agentAuthSidebarEnabled?: boolean;+ domainRegistrationEnabled?: boolean;+ distributionsEnabled?: boolean;+ hasBuiltintModels?: boolean;+ modelCostMultiplier?: number;+}+export interface SubscriptionProperties {+ tasks?: number | null;+ bonusTasks?: number | null;+ tiers?: any;+ price?: number;+ minimumChargedSeats?: number;+ freeCredits?: number;+ customModelsEnabled?: boolean;+ seatsIncluded?: number;+}diff --git a/packages/middleware/src/modules/quota/utils.ts b/packages/middleware/src/modules/quota/utils.tsnew file mode 100644index 00000000..370e21ab--- /dev/null+++ b/packages/middleware/src/modules/quota/utils.ts@@ -0,0 +1,52 @@+/* eslint-disable no-param-reassign */+import { PlanProperties, SubscriptionProperties } from './interfaces';++export const buildDefaultPlanProps: () => PlanProperties = () => {+ return {+ limits: {+ prodAiAgents: 10000,+ devAiAgents: 100000,+ spaces: 500,+ teamMembers: 1,+ dataPoolUsageGB: 4000,+ },+ flags: {+ embodimentsEnabled: true,+ agentAuthSidebarEnabled: true,+ domainRegistrationEnabled: true,+ distributionsEnabled: false,+ hasBuiltinModels: true,+ whitelabel: true,+ customModelsEnabled: true,+ modelCostMultiplier: 1,+ },+ };+};++export const buildDefaultSubscriptionProps: () => SubscriptionProperties = () => {+ return {+ tasks: null,+ bonusTasks: null,+ };+};++export const fillSubscriptionProps: (props: { [key: string]: any } | undefined) => SubscriptionProperties = props => {+ const defaults = buildDefaultSubscriptionProps();+ return {+ tasks: props?.tasks || defaults.tasks,+ };+};++export const fillPlanProps: (props: { [key: string]: any } | undefined) => PlanProperties = props => {+ const defaults = buildDefaultPlanProps();+ return {+ limits: {+ ...defaults.limits,+ ...(props?.limits || {}),+ },+ flags: {+ ...defaults.flags,+ ...(props?.flags || {}),+ },+ };+};diff --git a/packages/middleware/src/modules/subscription/constants.ts b/packages/middleware/src/modules/subscription/constants.tsnew file mode 100644index 00000000..689ed440--- /dev/null+++ b/packages/middleware/src/modules/subscription/constants.ts@@ -0,0 +1,18 @@+export const PLAN_METADATA_PREFIX = 'Plan_';+export const PLAN_SUBS_METADATA_PREFIX = 'Subs_';++export const PRICING_FLOW_VERSIONS = {+ V4: 'v4 Jan 2025',+} as const;++export type PricingFlowVersion = (typeof PRICING_FLOW_VERSIONS)[keyof typeof PRICING_FLOW_VERSIONS];++export const SUBS_ITEMS_TAGS = {+ TASKS_USAGE: 'tasks usage',+ SEATS_USAGE: 'user seats',+ BASE_PRICE: 'base price',+} as const;++export type SubsItemTag = (typeof SUBS_ITEMS_TAGS)[keyof typeof SUBS_ITEMS_TAGS];++export const FREE_USERS_FREE_CREDITS = 5;diff --git a/packages/middleware/src/modules/subscription/controllers/_sysapi/subscription.controller.m2m.ts b/packages/middleware/src/modules/subscription/controllers/_sysapi/subscription.controller.m2m.tsnew file mode 100644index 00000000..81438514--- /dev/null+++ b/packages/middleware/src/modules/subscription/controllers/_sysapi/subscription.controller.m2m.ts@@ -0,0 +1,25 @@+import httpStatus from 'http-status';+import { ExpressHandlerWithParams } from '../../../../../types';+import { subscriptionService } from '../../services';+import { PlanPropFlags, PlanPropLimits, PlanProperties, SubscriptionProperties } from '../../../quota/interfaces';+import ApiError from '../../../../utils/apiError';+import * as quotaUtils from '../../../quota/utils';++export const getTeamSubs: ExpressHandlerWithParams<+ {+ teamId: string;+ },+ {},+ any+> = async (req, res) => {+ const { teamId } = req.params;++ const subs = await subscriptionService.getTeamSubs(teamId);+ if (subs?.plan?.properties) {+ subs.plan.properties = quotaUtils.fillPlanProps(subs.plan.properties as object);+ }++ return res.status(httpStatus.OK).json({+ subs,+ });+};diff --git a/packages/middleware/src/modules/subscription/controllers/subscription.controller.ts b/packages/middleware/src/modules/subscription/controllers/subscription.controller.tsnew file mode 100644index 00000000..1e260554--- /dev/null+++ b/packages/middleware/src/modules/subscription/controllers/subscription.controller.ts@@ -0,0 +1,17 @@+import httpStatus from 'http-status';+import { ExpressHandler, ExpressHandlerWithParams } from '../../../../types';+import { subscriptionService } from '../services';+import ApiError from '../../../utils/apiError';+import { authExpressHelpers } from '../../auth/helpers/auth-express.helper';++export const getTeamsSubs: ExpressHandler<{}, { teamsSubs: any }> = async (req, res) => {+ const parentTeamId = authExpressHelpers.getParentTeamId(res);+ const includeObject: boolean = req.query.includeObject === 'true';++ const teamsSubs = await subscriptionService.getTeamSubs(parentTeamId, {}, includeObject);++ return res.status(httpStatus.OK).json({+ message: 'Teams Subs retrieved successfully',+ teamsSubs,+ });+};diff --git a/packages/middleware/src/modules/subscription/dto/plan.dto.ts b/packages/middleware/src/modules/subscription/dto/plan.dto.tsnew file mode 100644index 00000000..b684f2e1--- /dev/null+++ b/packages/middleware/src/modules/subscription/dto/plan.dto.ts@@ -0,0 +1,25 @@+import { PlanProperties } from '../../quota/interfaces';++export interface CreatePlanDto {+ plan: {+ name: string;+ price: number;+ stripeProductId: string;+ stripePriceId: string;+ properties: PlanProperties;+ isCustomPlan?: boolean;+ paid?: boolean;+ };+}++export interface EditPlanDto {+ id: number;+ plan: {+ name?: string;+ price?: number;+ stripeProductId?: string;+ stripePriceId?: string;+ properties?: Partial<PlanProperties>;+ paid?: boolean;+ };+}diff --git a/packages/middleware/src/modules/subscription/dto/subscription.dto.ts b/packages/middleware/src/modules/subscription/dto/subscription.dto.tsnew file mode 100644index 00000000..0663b29c--- /dev/null+++ b/packages/middleware/src/modules/subscription/dto/subscription.dto.ts@@ -0,0 +1,44 @@+import { SubscriptionProperties, PlanProperties } from '../../quota/interfaces';++export interface UpsertTeamSubsWithNewPlanDto {+ teamId: string;+ plan: {+ name: string;+ price: number;+ stripeProductId: string;+ stripePriceId: string;+ properties: PlanProperties;+ };+ stripeSubsId: string;+ sub?: {+ endAt?: Date;+ properties?: Partial<SubscriptionProperties>;+ billedAt?: Date;+ };+}++export interface EditTeamSubsDto {+ teamId: string;+ // plan?: {+ // name?: string;+ // price?: number;+ // stripeProductId?: string;+ // stripePriceId?: string;+ // properties?: Partial<PlanProperties>;+ // };+ stripeSubsId?: string;+ properties?: Partial<SubscriptionProperties>;+ endAt?: Date;+}++export interface ConnectTeamToExistingPlanDto {+ teamId: string;+ targetPlanId: number;+ stripeSubsId: string;+ sub?: {+ endAt?: Date;+ properties?: Partial<SubscriptionProperties>;+ billedAt?: Date;+ object?: { [key: string]: any };+ };+}diff --git a/packages/middleware/src/modules/subscription/interfaces.ts b/packages/middleware/src/modules/subscription/interfaces.tsnew file mode 100644index 00000000..86279125--- /dev/null+++ b/packages/middleware/src/modules/subscription/interfaces.ts@@ -0,0 +1,34 @@+import Stripe from 'stripe';++export type StripeEventDataWithMetadata = Stripe.CustomerSubscriptionCreatedEvent.Data & {+ object: {+ id: string;+ // customer: string;+ metadata: {+ // metadata goes here+ email?: string;+ teamId?: string;+ };+ };+};++export type StripeSubsCreatedEvent = Stripe.CustomerSubscriptionCreatedEvent & {+ data: StripeEventDataWithMetadata;+};++export type StripeCheckoutSessionCompletedEvent = Stripe.CheckoutSessionCompletedEvent & {+ data: {+ object: {+ metadata: {+ email: string;+ teamId: string;+ };+ };+ };+};++export interface WebhookCommand {+ execute(event: Stripe.EventBase & { [key: string]: any }): Promise<{ success: boolean; [key: string]: any }>;+}++export type PlanNames = 'Early Adopters' | 'SmythOS Starter' | 'SmythOS PRO' | 'SmythOS Free';diff --git a/packages/middleware/src/modules/subscription/middlewares/rate-limiters.mw.ts b/packages/middleware/src/modules/subscription/middlewares/rate-limiters.mw.tsnew file mode 100644index 00000000..27938252--- /dev/null+++ b/packages/middleware/src/modules/subscription/middlewares/rate-limiters.mw.ts@@ -0,0 +1,29 @@+import rateLimit from 'express-rate-limit';+import { authExpressHelpers } from '../../auth/helpers/auth-express.helper';+import { config } from '../../../../config/config';++const checkoutSessionsRateLimit = rateLimit({+ windowMs: 15 * 60 * 1000, // 15 minutes+ max: config.variables.env === 'production' ? 5 : 50,+ keyGenerator: (_, res) => {+ return authExpressHelpers.getTeamId(res);+ },+ standardHeaders: 'draft-7',+ legacyHeaders: false,++ requestPropertyName: 'teamId',+});++const billingSessionsRateLimit = rateLimit({+ windowMs: 15 * 60 * 1000, // 15 minutes+ max: config.variables.env === 'production' ? 5 : 50,+ keyGenerator: (_, res) => {+ return authExpressHelpers.getTeamId(res);+ },+ standardHeaders: 'draft-7',+ legacyHeaders: false,++ requestPropertyName: 'teamId',+});++export { checkoutSessionsRateLimit, billingSessionsRateLimit };diff --git a/packages/middleware/src/modules/subscription/routes/_sysapi/subscription.route.m2m.ts b/packages/middleware/src/modules/subscription/routes/_sysapi/subscription.route.m2m.tsnew file mode 100644index 00000000..b9711767--- /dev/null+++ b/packages/middleware/src/modules/subscription/routes/_sysapi/subscription.route.m2m.ts@@ -0,0 +1,11 @@+import { Router } from 'express';+import asyncHandler from 'express-async-handler';+import { validate } from '../../../../middlewares/validate.middleware';+import * as subsValidations from '../../validations/subscription.validation';+import * as subsController from '../../controllers/_sysapi/subscription.controller.m2m';++const router = Router();++router.get('/subscriptions/teams/:teamId', validate(subsValidations.getTeamSubs), asyncHandler(subsController.getTeamSubs));++export { router as _subscriptionRouter };diff --git a/packages/middleware/src/modules/subscription/routes/subscription.route.ts b/packages/middleware/src/modules/subscription/routes/subscription.route.tsnew file mode 100644index 00000000..8109c03e--- /dev/null+++ b/packages/middleware/src/modules/subscription/routes/subscription.route.ts@@ -0,0 +1,13 @@+import { Router, raw } from 'express';+import asyncHandler from 'express-async-handler';+import * as subsController from '../controllers/subscription.controller';+import { userAuthMiddleware } from '../../auth/middlewares/auth.middleware';+import { validate } from '../../../middlewares/validate.middleware';+import * as subsValidations from '../validations/subscription.validation';+import { billingSessionsRateLimit, checkoutSessionsRateLimit } from '../middlewares/rate-limiters.mw';++const router = Router();++router.get('/subscriptions/me', userAuthMiddleware, asyncHandler(subsController.getTeamsSubs));++export { router as subscriptionRouter };diff --git a/packages/middleware/src/modules/subscription/services/index.ts b/packages/middleware/src/modules/subscription/services/index.tsnew file mode 100644index 00000000..5347f164--- /dev/null+++ b/packages/middleware/src/modules/subscription/services/index.ts@@ -0,0 +1 @@+export * as subscriptionService from './subscription.service';diff --git a/packages/middleware/src/modules/subscription/services/subscription.service.ts b/packages/middleware/src/modules/subscription/services/subscription.service.tsnew file mode 100644index 00000000..7dc47ffd--- /dev/null+++ b/packages/middleware/src/modules/subscription/services/subscription.service.ts@@ -0,0 +1,110 @@+/* eslint-disable no-nested-ternary */+import { Transactional } from '../../../../types/service.type';+import httpStatus from 'http-status';+import { prisma } from '../../../../prisma/prisma-client';+import ApiError from '../../../utils/apiError';+import { PrismaTransaction } from '../../../../types';+import * as quotaUtils from '../../quota/utils';+import { startOfMonth, addMonths } from 'date-fns';+import { createLogger } from '../../../../config/logging-v2';++const LOGGER = createLogger('subscription.service.ts');++export const getTeamSubs = async (teamId: string, options?: { tx?: PrismaTransaction }, includeObject?: boolean) => {+ const _p = options?.tx || prisma;++ const team = await _p.team.findFirst({+ where: {+ id: teamId,+ },++ select: {+ subscriptionId: true,+ id: true,+ },+ });++ if (!team) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Team not found');+ }++ if (!team.subscriptionId) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Team does not have a subscription');+ }++ // RESET date will be the first day of the next month+ const resetTasksDate = startOfMonth(addMonths(new Date(), 1));++ const subs = await _p.subscription.findFirst({+ where: {+ id: team.subscriptionId,+ },++ select: {+ id: true,+ stripeId: true,+ status: true,+ properties: true,+ endDate: true,+ startDate: true,+ plan: {+ select: {+ id: true,+ name: true,+ price: true,+ stripeId: true,+ priceId: true,+ properties: true,+ paid: true,+ isCustomPlan: true,+ isDefaultPlan: true,+ friendlyName: true,+ },+ },+ ...(includeObject ? { object: true } : {}),+ },+ });++ if (subs.plan?.friendlyName) {+ subs.plan.name = subs.plan.friendlyName; // for backward compatibility+ }++ return {+ ...subs,+ object: {},+ resetDate: resetTasksDate,+ };+};++export const retrieveDefaultPlan = async ({ ctx }: Transactional) => {+ const _tx = ctx?.tx || prisma;++ let freePlan = await _tx.plan.findFirst({+ where: {+ isDefaultPlan: true,+ },+ select: {+ id: true,+ },+ });++ if (!freePlan) {+ LOGGER.info(`FREE PLAN DOESN'T EXIST. CREATING...`);+ freePlan = await _tx.plan.create({+ data: {+ name: 'Free',+ price: 0,+ paid: false,+ isDefaultPlan: true,+ stripeId: 'no-id',+ priceId: 'no-id',+ properties: quotaUtils.buildDefaultPlanProps(),+ },+ select: {+ id: true,+ },+ });+ }++ return freePlan;+};diff --git a/packages/middleware/src/modules/subscription/validations/subscription.validation.ts b/packages/middleware/src/modules/subscription/validations/subscription.validation.tsnew file mode 100644index 00000000..6403a730--- /dev/null+++ b/packages/middleware/src/modules/subscription/validations/subscription.validation.ts@@ -0,0 +1,7 @@+import Joi from 'joi';++export const getTeamSubs = {+ params: Joi.object({+ teamId: Joi.string().required(),+ }),+};diff --git a/packages/middleware/src/modules/team/constants.ts b/packages/middleware/src/modules/team/constants.tsnew file mode 100644index 00000000..d51abc17--- /dev/null+++ b/packages/middleware/src/modules/team/constants.ts@@ -0,0 +1,4 @@+export const _TEAM_SETTINGS_KEYS = {+ BILLING_LIMIT: 'billingLimit',+ HAS_SENT_QUOTA_REACHED_EMAIL: 'hasSentQuotaReachedEmail',+} as const;diff --git a/packages/middleware/src/modules/team/constants/roles.constants.ts b/packages/middleware/src/modules/team/constants/roles.constants.tsnew file mode 100644index 00000000..5882e3e3--- /dev/null+++ b/packages/middleware/src/modules/team/constants/roles.constants.ts@@ -0,0 +1,28 @@+import { TeamRole } from '@prisma/client';++// These roles are added on top of the Super Admin role.+export const DEFAULT_ROLES: Record<string, Partial<TeamRole>> = {+ View: {+ name: 'View',+ canManageTeam: false,+ acl: {+ default_role: 'view',+ },+ },+ Edit: {+ name: 'Edit',+ canManageTeam: false,+ acl: {+ default_role: 'edit',+ },+ },+ Admin: {+ name: 'Admin',+ canManageTeam: true,+ acl: {+ default_role: 'admin',+ },+ },+};++export const DEFAULT_ROLE_POSTFIX = '(built-in role)';diff --git a/packages/middleware/src/modules/team/controllers/_sysapi/team.controller.ts b/packages/middleware/src/modules/team/controllers/_sysapi/team.controller.tsnew file mode 100644index 00000000..e6bf691e--- /dev/null+++ b/packages/middleware/src/modules/team/controllers/_sysapi/team.controller.ts@@ -0,0 +1,114 @@+// TEAM SETTINGS++import httpStatus from 'http-status';+import { ExpressHandler, ExpressHandlerWithParams } from '../../../../../types';+import { teamService, teamSettingsService } from '../../services';++export const getSettings: ExpressHandlerWithParams<+ {+ teamId: string;+ },+ {},+ {+ settings: any[];+ }+> = async (req, res) => {+ const teamId = req.params.teamId;+ const settings = await teamSettingsService.getSettings(teamId);+ return res.json({+ message: 'Settings retrieved successfully',+ settings,+ });+};++export const getSetting: ExpressHandlerWithParams<+ {+ settingKey: string;+ teamId: string;+ },+ {},+ {+ setting: any;+ }+> = async (req, res) => {+ const teamId = req.params.teamId;+ const { settingKey } = req.params;+ const setting = await teamSettingsService.getSetting(teamId, settingKey);+ res.json({+ message: 'Setting retrieved successfully',+ setting,+ });+};++export const getTeamInfo: ExpressHandler<+ {},+ {+ team: any;+ }+> = async (req, res) => {+ const teamId = req.params.teamId;+ const team = await teamService.getTeamDetailsM2M(teamId);++ res.status(httpStatus.OK).json({+ message: 'Team retrieved successfully',+ team,+ });+};++export const getTeamsM2M: ExpressHandlerWithParams<+ {},+ {},+ {+ teams: any[];+ total: number;+ }+> = async (req, res) => {+ const { page, limit, email } = req.query;+ const { teams, count } = await teamService.listTeamsM2M({+ pagination: {+ page,+ limit,+ },+ emailSearchTerm: email,+ });++ res.status(httpStatus.OK).json({+ message: 'Teams retrieved successfully',+ teams,+ total: count,+ });+};++export const createSettingM2M: ExpressHandlerWithParams<+ { teamId: string },+ {+ settingKey: string;+ settingValue: string;+ },+ {+ setting: any;+ }+> = async (req, res) => {+ const { settingKey, settingValue } = req.body;+ const { teamId } = req.params;+ const newSetting = await teamSettingsService.createSetting(teamId, settingKey, settingValue);+ res.json({+ message: 'Setting updated successfully',+ setting: newSetting,+ });+};++export const deleteSettingM2M: ExpressHandlerWithParams<+ {+ settingKey: string;+ teamId: string;+ },+ {},+ {}+> = async (req, res) => {+ const { settingKey, teamId } = req.params;+ const deletedSetting = await teamSettingsService.deleteSetting(teamId, settingKey);+ res.json({+ message: 'Setting deleted successfully',+ });+};diff --git a/packages/middleware/src/modules/team/controllers/team.controller.ts b/packages/middleware/src/modules/team/controllers/team.controller.tsnew file mode 100644index 00000000..aaa08c08--- /dev/null+++ b/packages/middleware/src/modules/team/controllers/team.controller.ts@@ -0,0 +1,350 @@+import httpStatus from 'http-status';+import { DEFAULT_ROLE_POSTFIX, DEFAULT_ROLES } from '../constants/roles.constants';+import { ExpressHandler, ExpressHandlerWithParams } from '../../../../types';+import { teamService, teamSettingsService } from '../services';+import { authExpressHelpers } from '../../auth/helpers/auth-express.helper';++// Function to ensure default roles exist and return any newly created roles+async function ensureDefaultRoles(teamId: string, existingRoles: any[]): Promise<any[]> {+ const newRoles = [];++ // Filter default roles+ const defaultRoles = existingRoles.filter(role => role.acl?.default_role);+ async function createRole(name: string, roleData: any) {+ const newRole = await teamService.createTeamRole({+ teamId,+ name,+ acl: roleData.acl as object,+ canManageTeam: roleData.canManageTeam,+ });+ newRoles.push(newRole);+ }++ // Check for missing default roles+ for (const [roleName, roleData] of Object.entries(DEFAULT_ROLES)) {+ const existingDefaultRole = defaultRoles.find(+ role => role.name.toLowerCase() === roleName.toLowerCase() || role.name.toLowerCase() === `${roleName.toLowerCase()} ${DEFAULT_ROLE_POSTFIX}`,+ );++ if (!existingDefaultRole) {+ await createRole(roleName, roleData);+ }+ }++ return newRoles;+}++export const getTeamInfo: ExpressHandler<+ {},+ {+ team: any;+ }+> = async (req, res) => {+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ const team = await teamService.getTeamDetails(teamId);++ res.status(httpStatus.OK).json({+ message: 'Team retrieved successfully',+ team: {+ ...team,+ userId,+ },+ });+};++export const getMembers: ExpressHandler<+ {},+ {+ members: any;+ }+> = async (req, res) => {+ const { includeRoles } = req.query;+ const teamId = authExpressHelpers.getTeamId(res);++ const members = await teamService.listMembers(teamId, {+ includeRoles: includeRoles === 'true',+ });++ res.status(httpStatus.OK).json({+ message: 'Members retrieved successfully',+ members,+ });+};++export const getMyRoles: ExpressHandler<+ {},+ {+ role: any;+ }+> = async (req, res) => {+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ const role = await teamService.getMemberRole(userId, teamId);++ res.status(httpStatus.OK).json({+ message: 'Role retrieved successfully',+ role,+ });+};++export const updateMemberRole: ExpressHandlerWithParams<+ {+ memberId: string;+ },+ {+ roleId?: number;+ userSpecificAcl?: object;+ },+ {+ message: string;+ }+> = async (req, res) => {+ const { memberId } = req.params;+ const { roleId, userSpecificAcl } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ // await teamService.checkIfCanManageTeamOrThrow(userId, teamId);+ await teamService.updateMemberRole({+ teamId,+ caller: { userId },+ member: { userId: +memberId, newRoleId: roleId },+ });++ res.status(httpStatus.OK).json({+ message: 'Member role updated successfully',+ });+};++export const updateMemberSpecificAcl: ExpressHandler<+ {+ memberId: number;+ userSpecificAcl: object;+ },+ {+ message: string;+ }+> = async (req, res) => {+ const { memberId, userSpecificAcl } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ await teamService.checkMemberExistsOrThrow(+memberId, teamId);+ // await teamService.checkIfCanManageTeamOrThrow(userId, teamId);+ await teamService.updateMemberSpecificAcl({+ memberId,+ teamId,+ userSpecificAcl,+ });++ res.status(httpStatus.OK).json({+ message: 'Member role updated successfully',+ });+};++export const getTeamRoles: ExpressHandler<+ {},+ {+ roles: any;+ }+> = async (req, res) => {+ const teamId = authExpressHelpers.getTeamId(res);+ // Fetch all roles+ let roles = await teamService.listAllTeamRoles(teamId);++ // Ensure default roles exist and get any newly created roles+ const newRoles = await ensureDefaultRoles(teamId, roles);++ // Combine existing roles with any new roles+ roles = [...roles, ...newRoles];++ res.status(httpStatus.OK).json({+ message: 'Roles retrieved successfully',+ roles,+ });+};++export const createTeamRole: ExpressHandler<+ {+ name: string;+ canManageTeam: boolean;+ acl: object;+ },+ {+ role: any;+ }+> = async (req, res) => {+ const { name, canManageTeam, acl } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ const role = await teamService.createTeamRole({+ name,+ canManageTeam,+ acl,+ teamId,+ });++ res.status(httpStatus.OK).json({+ message: 'Role created successfully',+ role,+ });+};++export const getTeamRole: ExpressHandler<+ {+ roleId: number;+ },+ {+ role: any;+ }+> = async (req, res) => {+ const { roleId } = req.params;+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ const role = await teamService.getTeamRole(+roleId, teamId);++ res.status(httpStatus.OK).json({+ message: 'Role retrieved successfully',+ role,+ });+};++export const deleteTeamRole: ExpressHandler<+ {+ roleId: number;+ },+ {+ message: string;+ }+> = async (req, res) => {+ const { roleId } = req.params;+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ await teamService.deleteTeamRole(+roleId, teamId);++ res.status(httpStatus.OK).json({+ message: 'Role deleted successfully',+ });+};++export const updateTeamRole: ExpressHandler<+ {+ roleId: number;+ name?: string;+ canManageTeam?: boolean;+ acl?: object;+ },+ {+ role: any;+ }+> = async (req, res) => {+ const { name, canManageTeam, acl, roleId } = req.body;+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ const role = await teamService.updateTeamRole({+ roleId: +roleId,+ name,+ canManageTeam,+ acl,+ teamId,+ });++ res.status(httpStatus.OK).json({+ message: 'Role updated successfully',+ role,+ });+};++// TEAM SETTINGS++export const getSettings: ExpressHandler<+ {},+ {+ settings: any[];+ }+> = async (req, res) => {+ const teamId = authExpressHelpers.getTeamId(res);+ const settings = await teamSettingsService.getSettings(teamId);+ return res.json({+ message: 'Settings retrieved successfully',+ settings,+ });+};++export const getSetting: ExpressHandlerWithParams<+ {+ settingKey: string;+ },+ {},+ {+ setting: any;+ }+> = async (req, res) => {+ const teamId = authExpressHelpers.getTeamId(res);+ const { settingKey } = req.params;+ const setting = await teamSettingsService.getSetting(teamId, settingKey);+ res.json({+ message: 'Setting retrieved successfully',+ setting,+ });+};++export const createSetting: ExpressHandler<+ {+ settingKey: string;+ settingValue: string;+ },+ {+ setting: any;+ }+> = async (req, res) => {+ const teamId = authExpressHelpers.getTeamId(res);+ const { settingKey, settingValue } = req.body;+ const newSetting = await teamSettingsService.createSetting(teamId, settingKey, settingValue);+ res.json({+ message: 'Setting updated successfully',+ setting: newSetting,+ });+};++export const deleteSetting: ExpressHandlerWithParams<+ {+ settingKey: string;+ },+ {},+ {}+> = async (req, res) => {+ const teamId = authExpressHelpers.getTeamId(res);+ const { settingKey } = req.params;+ const deletedSetting = await teamSettingsService.deleteSetting(teamId, settingKey);+ res.json({+ message: 'Setting deleted successfully',+ });+};++export const getAllTeams: ExpressHandlerWithParams<+ {+ id: string;+ },+ {},+ {+ teams: any[];+ }+> = async (req, res) => {+ const { id } = req.params;+ const userId = authExpressHelpers.getUserId(res);++ const teams = await teamService.getAllTeams(id, userId);++ res.status(httpStatus.OK).json({+ message: 'Teams retrieved successfully',+ ...teams,+ });+};diff --git a/packages/middleware/src/modules/team/middlewares/teams.middleware.ts b/packages/middleware/src/modules/team/middlewares/teams.middleware.tsnew file mode 100644index 00000000..1e94bf62--- /dev/null+++ b/packages/middleware/src/modules/team/middlewares/teams.middleware.ts@@ -0,0 +1,17 @@+import asyncHandler from 'express-async-handler';+import { ExpressHandler } from '../../../../types';+import { teamService } from '../services';+import { authExpressHelpers } from '../../auth/helpers/auth-express.helper';+import ApiError from '../../../utils/apiError';+import httpStatus from 'http-status';++export const requireTeamManager: ExpressHandler<{}, {}> = asyncHandler(async (req, res, next) => {+ const teamId = authExpressHelpers.getTeamId(res);+ const userId = authExpressHelpers.getUserId(res);++ if (!teamId || !userId) {+ throw new ApiError(httpStatus.BAD_REQUEST, 'User or team not found');+ }+ await teamService.checkIfCanManageTeamOrThrow(userId, teamId);+ next();+});diff --git a/packages/middleware/src/modules/team/routes/_sysapi/team.route.ts b/packages/middleware/src/modules/team/routes/_sysapi/team.route.tsnew file mode 100644index 00000000..a91e8700--- /dev/null+++ b/packages/middleware/src/modules/team/routes/_sysapi/team.route.ts@@ -0,0 +1,25 @@+import { Router } from 'express';+import asyncHandler from 'express-async-handler';+import * as teamM2MController from '../../controllers/_sysapi/team.controller';+import { validate } from '../../../../middlewares/validate.middleware';+import * as teamsValidations from '../../validations/team.validation';++const router = Router();++router.get('/teams/:teamId', validate(teamsValidations.getTeamInfoM2M), asyncHandler(teamM2MController.getTeamInfo));++router.get('/teams', validate(teamsValidations.getTeamsM2M), asyncHandler(teamM2MController.getTeamsM2M));++router.get('/teams/:teamId/settings', validate(teamsValidations.getSettingsM2M), asyncHandler(teamM2MController.getSettings));+router.get('/teams/:teamId/settings/:settingKey', validate(teamsValidations.getSettingM2M), asyncHandler(teamM2MController.getSetting));++router.put('/teams/:teamId/settings', validate(teamsValidations.createSettingM2M), asyncHandler(teamM2MController.createSettingM2M));++router.delete(+ '/teams/:teamId/settings/:settingKey',++ validate(teamsValidations.deleteSettingM2M),+ asyncHandler(teamM2MController.deleteSettingM2M),+);++export { router as _teamRouter };diff --git a/packages/middleware/src/modules/team/routes/team.route.ts b/packages/middleware/src/modules/team/routes/team.route.tsnew file mode 100644index 00000000..d8d05d1f--- /dev/null+++ b/packages/middleware/src/modules/team/routes/team.route.ts@@ -0,0 +1,40 @@+import { Router } from 'express';+import asyncHandler from 'express-async-handler';+import * as teamController from '../controllers/team.controller';+import { validate } from '../../../middlewares/validate.middleware';+import * as teamsValidations from '../validations/team.validation';+import { authMiddlewareFactory, userAuthMiddleware } from '../../auth/middlewares/auth.middleware';+import { requireTeamManager } from '../middlewares/teams.middleware';++const router = Router();++// TODO: move the `requireTeamManager` middleware check into the service layer++router.get('/teams/me', userAuthMiddleware, asyncHandler(teamController.getTeamInfo));++router.get('/teams/members', userAuthMiddleware, asyncHandler(teamController.getMembers));++router.put(+ '/teams/members/:memberId/role',+ userAuthMiddleware,+ validate(teamsValidations.updateMemberRole),+ asyncHandler(teamController.updateMemberRole),+);++router.get('/teams/roles/me', userAuthMiddleware, asyncHandler(teamController.getMyRoles));++router.get('/teams/roles', [userAuthMiddleware, requireTeamManager], asyncHandler(teamController.getTeamRoles));++router.get('/teams/settings', [userAuthMiddleware], asyncHandler(teamController.getSettings));+router.get('/teams/settings/:settingKey', [userAuthMiddleware], validate(teamsValidations.getSetting), asyncHandler(teamController.getSetting));+router.put('/teams/settings', [userAuthMiddleware], validate(teamsValidations.createSetting), asyncHandler(teamController.createSetting));++router.delete(+ '/teams/settings/:settingKey',+ [userAuthMiddleware],+ validate(teamsValidations.deleteSetting),+ asyncHandler(teamController.deleteSetting),+);++router.get('/teams/me/all/:id', userAuthMiddleware, asyncHandler(teamController.getAllTeams));+export { router as teamRouter };diff --git a/packages/middleware/src/modules/team/services/index.ts b/packages/middleware/src/modules/team/services/index.tsnew file mode 100644index 00000000..354b7f51--- /dev/null+++ b/packages/middleware/src/modules/team/services/index.ts@@ -0,0 +1,2 @@+export * as teamService from './team.service';+export * as teamSettingsService from './settings.team.service';diff --git a/packages/middleware/src/modules/team/services/settings.team.service.ts b/packages/middleware/src/modules/team/services/settings.team.service.tsnew file mode 100644index 00000000..814d1c29--- /dev/null+++ b/packages/middleware/src/modules/team/services/settings.team.service.ts@@ -0,0 +1,93 @@+import ApiError from '../../../utils/apiError';+import { prisma } from '../../../../prisma/prisma-client';++export async function getSettings(teamId: string): Promise<any[]> {+ return prisma.teamSetting.findMany({+ where: { teamId },+ select: {+ id: true,+ settingKey: true,+ settingValue: true,+ updatedAt: true,+ },+ });+}++export async function createSetting(teamId: string, settingKey: string, settingValue: string): Promise<any> {+ const existingSetting = await prisma.teamSetting.findFirst({+ where: {+ settingKey,+ teamId,+ },+ });++ if (existingSetting) {+ return prisma.teamSetting.update({+ where: {+ id: existingSetting.id,+ },+ data: {+ settingValue,+ },++ select: {+ id: true,+ settingKey: true,+ settingValue: true,+ updatedAt: true,+ },+ });+ }++ return prisma.teamSetting.create({+ data: {+ team: { connect: { id: teamId } },+ settingKey,+ settingValue,+ },++ select: {+ id: true,+ settingKey: true,+ settingValue: true,+ updatedAt: true,+ },+ });+}++export async function getSetting(teamId: string, settingKey: string): Promise<any> {+ const setting = await prisma.teamSetting.findFirst({+ where: {+ settingKey,+ teamId,+ },++ select: {+ id: true,+ settingKey: true,+ settingValue: true,+ updatedAt: true,+ },+ });++ if (!setting) {+ throw new ApiError(404, 'Setting not found');+ }++ return setting;+}++export async function deleteSetting(teamId: string, settingKey: string) {+ const deleted = await prisma.teamSetting.deleteMany({+ where: {+ teamId,+ settingKey,+ },+ });++ if (deleted.count === 0) {+ throw new ApiError(404, 'Setting not found');+ }++ return deleted;+}diff --git a/packages/middleware/src/modules/team/services/team.service.ts b/packages/middleware/src/modules/team/services/team.service.tsnew file mode 100644index 00000000..a97bfd1c--- /dev/null+++ b/packages/middleware/src/modules/team/services/team.service.ts@@ -0,0 +1,1063 @@+/* eslint-disable @typescript-eslint/no-empty-function */+import { prisma } from '../../../../prisma/prisma-client';+import ApiError from '../../../utils/apiError';+import httpStatus from 'http-status';+import { PrismaTransaction, Transactional } from '../../../../types';+import errKeys from '../../../utils/errorKeys';+import { includePagination, PRISMA_ERROR_CODES } from '../../../utils/general';+import * as quotaUtils from '../../quota/utils';+import { retrieveDefaultPlan } from '../../subscription/services/subscription.service';+import { subscriptionService } from '../../subscription/services';+import { LOGGER } from '../../../../config/logging';+import { config } from '../../../../config/config';++export const createUserTeam = async ({+ name,+ userId,+ options,+}: {+ name?: string;+ userId: number;+ options?: {+ tx?: PrismaTransaction;+ };+}) => {+ const runOperations = async (tx: PrismaTransaction) => {+ // let defaultPlan = await tx.plan.findFirst({+ // where: {+ // isDefaultPlan: true,+ // },+ // select: {+ // id: true,+ // },+ // });++ // if (!defaultPlan) {+ // defaultPlan = await tx.plan.create({+ // data: {+ // name: 'Free Plan',+ // price: 0,+ // stripeId: 'no-id',+ // isDefaultPlan: true,+ // priceId: 'no-id',+ // },+ // select: {+ // id: true,+ // },+ // });+ // }++ const defaultPlan = await retrieveDefaultPlan({});++ const team = await tx.team.create({+ data: {+ name: name ?? 'My Team',+ subscription: {+ create: {+ startDate: new Date(),+ stripeId: '',+ status: 'ACTIVE',+ plan: {+ connect: {+ id: defaultPlan.id,+ },+ },+ },+ },++ users: {+ connect: {+ id: userId,+ },+ },+ },++ select: {+ id: true,+ },+ });++ const superAdminRole = await tx.teamRole.create({+ data: {+ // super admin role+ name: 'Super Admin',+ isOwnerRole: true,+ canManageTeam: true,+ teamId: team.id,+ },++ select: {+ id: true,+ },+ });++ // assign the user to the super admin role+ await tx.userTeamRole.create({+ data: {+ user: {+ connect: {+ id: userId,+ },+ },+ sharedTeamRole: {+ connect: {+ id: superAdminRole.id,+ },+ },+ isTeamInitiator: true,+ },+ });++ return team;+ };++ let team: { id: string };+ if (options?.tx) {+ team = await runOperations(options.tx);+ } else {+ team = await prisma.$transaction(runOperations, {+ timeout: 30_000, // 30 second timeout+ maxWait: 10_000, // 10 second max wait+ });+ }++ return team;+};++export const listMembers = async (+ teamId: string,+ options?: {+ includeRoles?: boolean;+ },+) => {+ const includeRolesFields = {+ where: {+ sharedTeamRole: {+ teamId,+ },+ },+ select: {+ userSpecificAcl: true,+ isTeamInitiator: true,++ sharedTeamRole: {+ select: {+ acl: true,+ name: true,+ id: true,+ isOwnerRole: true,+ canManageTeam: true,+ },+ },+ },+ };++ let members = await prisma.user.findMany({+ where: {+ userTeamRole: {+ some: {+ sharedTeamRole: {+ teamId,+ },+ },+ },+ },+ select: {+ id: true,+ name: true,+ email: true,+ createdAt: true,+ avatar: true,++ ...(options?.includeRoles ? { userTeamRole: includeRolesFields } : {}),+ },+ });++ if (options?.includeRoles) {+ // @ts-ignore+ members = members.map(member => ({+ ...member,+ userTeamRole: member.userTeamRole[0],+ }));+ }++ return members;+};++export const isUserPartOfTeam = async (userId: number, teamId: string) => {+ if (!userId || !teamId) {+ LOGGER.error(new Error('isUserPartOfTeam: userId or teamId is missing'));+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, 'Internal error');+ }+ // check if the user is part of the team+ const user = await prisma.user.findUnique({+ where: {+ id: userId,+ userTeamRole: {+ some: {+ sharedTeamRole: {+ teamId,+ },+ },+ },+ },+ select: {+ id: true,+ },+ });++ return !!user;+};++export const getTeamDetails = async (teamId: string) => {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ },+ select: {+ id: true,+ name: true,+ parentId: true,+ subscription: {+ select: {+ id: true,+ status: true,+ plan: {+ select: {+ id: true,+ name: true,+ price: true,+ stripeId: true,+ properties: true,+ isDefaultPlan: true,+ friendlyName: true,+ },+ },+ properties: true,+ endDate: true,+ startDate: true,+ updatedAt: true,+ },+ },+ },+ });++ const owner = await getTeamOwner({ teamId });++ return {+ ...team,+ owner,+ };+};+export const getTeamDetailsM2M = async (teamId: string) => {+ const team = await prisma.team.findUnique({+ where: {+ id: teamId,+ },+ select: {+ id: true,+ name: true,+ subscription: {+ select: {+ id: true,+ status: true,+ plan: {+ select: {+ id: true,+ name: true,+ price: true,+ stripeId: true,+ },+ },+ endDate: true,+ startDate: true,+ updatedAt: true,+ },+ },++ subTeams: {+ select: {+ id: true,+ name: true,+ },+ },+ parentId: true,++ salt: true,+ },+ });++ return team;+};++export const listAllTeamRoles = async (teamId: string) => {+ const roles = await prisma.teamRole.findMany({+ where: {+ teamId,+ },+ select: {+ id: true,+ name: true,+ isOwnerRole: true,+ canManageTeam: true,+ acl: true,++ userTeamRole: {+ select: {+ user: {+ select: {+ avatar: true,+ email: true,+ id: true,+ name: true,+ },+ },+ },+ },+ },+ });++ return roles;+};++export const getTeamRole = async (roleId: number, teamId: string) => {+ const role = await prisma.teamRole+ .findUniqueOrThrow({+ where: {+ id: roleId,+ teamId,+ },+ select: {+ id: true,+ name: true,+ isOwnerRole: true,+ canManageTeam: true,+ acl: true,+ },+ })+ .catch(err => {+ if (err.code === PRISMA_ERROR_CODES.NON_EXISTENT_RECORD) throw new ApiError(httpStatus.NOT_FOUND, 'Role not found');+ throw err;+ });++ return role;+};++//+export const createTeamRole = async ({ name, canManageTeam, acl, teamId }: { name: string; canManageTeam: boolean; acl: object; teamId: string }) => {+ const role = await prisma.teamRole.create({+ data: {+ name,+ canManageTeam,+ acl,+ team: {+ connect: {+ id: teamId,+ },+ },+ },+ select: {+ id: true,+ name: true,+ isOwnerRole: true,+ canManageTeam: true,+ acl: true,+ },+ });++ return role;+};++export const updateTeamRole = async ({+ roleId,+ name,+ canManageTeam,+ acl,+ teamId,+}: {+ roleId: number;+ name?: string;+ canManageTeam?: boolean;+ acl?: object;+ teamId: string;+}) => {+ await checkTeamRoleExistsOrThrow(+roleId, teamId);++ // check if the user with the "canManageTeam" permission is trying to update the+ // role of the team initiator (the user who created the team)+ // if so, throw an error because the role of the team initiator cannot be removed from the team+ //* CAN BE CHANGED IN THE FUTURE++ // TODO: refactor this to only get the role id and isOwnerRole+ const teamInitiatorRole = await prisma.userTeamRole.findFirst({+ where: {+ isTeamInitiator: true,+ sharedTeamRole: {+ teamId,+ },+ },+ select: {+ isTeamInitiator: true,+ sharedTeamRole: {+ select: {+ id: true,+ isOwnerRole: true,+ },+ },+ },+ });++ if (teamInitiatorRole?.sharedTeamRole.id === roleId) {+ throw new ApiError(httpStatus.FORBIDDEN, 'You cannot update the role of the team owner');+ }++ const role = await prisma.teamRole.update({+ where: {+ teamId_id: {+ teamId,+ id: roleId,+ },+ },+ data: {+ name,+ canManageTeam,+ acl,+ },+ select: {+ id: true,+ name: true,+ isOwnerRole: true,+ canManageTeam: true,+ acl: true,+ },+ });++ return role;+};++export const deleteTeamRole = async (roleId: number, teamId: string) => {+ // check if any relations(users) are using this role+ // if so, throw an error++ const role = await prisma.teamRole.findFirst({+ where: {+ id: roleId,+ teamId,+ },+ select: {+ _count: {+ select: {+ userTeamRole: true,+ },+ },+ },+ });++ if (role?._count?.userTeamRole) {+ throw new ApiError(httpStatus.FORBIDDEN, 'Cannot delete role. It is being used by some members');+ }++ const deleted = await prisma.teamRole.deleteMany({+ where: {+ id: roleId,+ teamId,+ },+ });++ if (!deleted.count) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Role not found');+ }+};++// user roles+export const getMemberRole = async (userId: number, teamId: string) => {+ const roles = await prisma.userTeamRole.findFirst({+ where: {+ userId,+ sharedTeamRole: {+ teamId,+ },+ },+ select: {+ sharedTeamRole: {+ select: {+ id: true,+ name: true,+ isOwnerRole: true,+ canManageTeam: true,+ acl: true,+ },+ },+ isTeamInitiator: true,+ roleId: true,+ userSpecificAcl: true,+ userId: true,+ },+ });++ return roles;+};++export const updateMemberRole = async ({+ member,+ caller,+ teamId,+}: {+ member: {+ userId: number;+ newRoleId?: number;+ };++ caller: {+ userId: number;+ };++ teamId: string;+}) => {+ await checkMemberExistsOrThrow(+member.userId, teamId);++ const currentMemberTeamRole = await prisma.userTeamRole.findFirst({+ where: {+ userId: member.userId,+ sharedTeamRole: {+ teamId,+ },+ },+ select: {+ isTeamInitiator: true,+ sharedTeamRole: {+ select: {+ canManageTeam: true,+ },+ },+ },+ });++ if (currentMemberTeamRole?.isTeamInitiator) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Team initiator role cannot be updated');+ }++ const currentTeamRole = await prisma.teamRole.findFirst({+ where: {+ teamId,+ userTeamRole: {+ some: {+ userId: member.userId,+ },+ },+ },+ select: {+ isOwnerRole: true,+ canManageTeam: true,+ id: true,+ },+ });++ const newTeamRole = await prisma.teamRole.findFirst({+ where: {+ teamId,+ id: member.newRoleId,+ },+ select: {+ isOwnerRole: true,+ canManageTeam: true,+ id: true,+ },+ });++ const callerTeamRole = await prisma.teamRole.findFirst({+ where: {+ teamId,+ userTeamRole: {+ some: {+ userId: caller.userId,+ },+ },+ },+ select: {+ isOwnerRole: true,+ canManageTeam: true,+ },+ });++ if (!newTeamRole) {+ throw new ApiError(httpStatus.NOT_FOUND, 'New role not found');+ }+ //* Super Admin in this context means: anyone who cannot be removed from the team++ // if caller is trying to update their own role+ if (caller.userId === member.userId) {+ throw new ApiError(httpStatus.FORBIDDEN, 'You cannot update your own role');+ }++ // if (!callerTeamRole!.canManageTeam) {+ // throw new ApiError(httpStatus.FORBIDDEN, 'You do not have permission to update member roles');+ // }++ // if the member's new role is a can manage team and the caller cannot, throw an error+ if (newTeamRole.canManageTeam === true && callerTeamRole!.canManageTeam === false) {+ throw new ApiError(httpStatus.FORBIDDEN, 'You cannot update this member role');+ }++ const role = await prisma.userTeamRole.update({+ where: {+ userId_roleId: {+ userId: member.userId,+ roleId: currentTeamRole!.id,+ },+ },+ data: {+ ...(newTeamRole.id+ ? {+ sharedTeamRole: {+ connect: {+ id: newTeamRole.id,+ },+ },+ }+ : {}),+ },+ });++ return role;+};++export const updateMemberSpecificAcl = async ({+ memberId,+ teamId,+ userSpecificAcl,+}: {+ memberId: number;+ teamId: string;+ userSpecificAcl: object;+}) => {+ const exisitingRole = await prisma.userTeamRole.findFirstOrThrow({+ where: {+ userId: memberId,+ sharedTeamRole: {+ teamId,+ },+ },+ select: {+ roleId: true,+ },+ });++ const role = await prisma.userTeamRole.update({+ where: {+ userId_roleId: {+ userId: memberId,+ roleId: exisitingRole.roleId,+ },+ },+ data: {+ userSpecificAcl,+ },+ });++ return role;+};++export const checkMemberExistsOrThrow = async (memberId: number, teamId: string, options?: { tx?: PrismaTransaction }) => {+ // eslint-disable-next-line no-underscore-dangle+ const _prisma = options?.tx ?? prisma;++ const member = await _prisma.user.findFirst({+ where: {+ id: memberId,+ // teamId,+ userTeamRole: {+ some: {+ sharedTeamRole: {+ teamId,+ },+ },+ },+ },++ select: {+ id: true,+ },+ });++ if (!member) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Member not found');+ }++ return member;+};++export const checkIfCanManageTeamOrThrow = async (userId: number, teamId: string) => {+ const role = await prisma.userTeamRole.findFirst({+ where: {+ userId,+ sharedTeamRole: {+ teamId,+ canManageTeam: true,+ },+ },++ select: {+ roleId: true,+ },+ });++ if (!role) {+ throw new ApiError(httpStatus.FORBIDDEN, 'You do not have permission to perform this action', errKeys.NOT_ENOUGH_PERMISSIONS);+ }++ return role;+};++export const checkTeamRoleExistsOrThrow = async (+ roleId: number,+ teamId: string,+ options?: {+ tx?: PrismaTransaction;+ },+) => {+ const _p = options?.tx || prisma;+ const role = await _p.teamRole.findUnique({+ where: {+ teamId_id: {+ teamId,+ id: roleId,+ },+ },+ select: {+ id: true,+ },+ });++ if (!role) {+ throw new ApiError(httpStatus.NOT_FOUND, 'Role not found');+ }++ return role;+};++/**+ * Deletes all user team roles for a given user team (parent team) and its sub-teams+ */+export const deleteUserTeamRoles = async ({+ parentTeamId,+ userId,+ options,+}: {+ parentTeamId: string;+ userId: number;+ options?: { tx?: PrismaTransaction };+}) => {+ const runOperations = async (tx: PrismaTransaction) => {+ const userRoles = await tx.userTeamRole.findMany({+ where: {+ userId,+ },+ select: {+ roleId: true,+ sharedTeamRole: {+ select: {+ team: {+ select: {+ id: true,+ parentId: true,+ },+ },+ },+ },+ },+ });+ const rolesToDelete = userRoles.filter(r => r.sharedTeamRole.team.parentId === parentTeamId || r.sharedTeamRole.team.id === parentTeamId);++ await tx.userTeamRole.deleteMany({+ where: {+ userId,+ roleId: {+ in: rolesToDelete.map(r => r.roleId),+ },+ },+ });+ };++ if (options?.tx) {+ await runOperations(options.tx);+ } else {+ await prisma.$transaction(runOperations);+ }+};++export const getTeamOwner = async ({ teamId, ctx }: Transactional<{ teamId: string }>) => {+ const _tx = ctx?.tx ?? prisma;++ const owner = await _tx.user.findFirstOrThrow({+ where: {+ userTeamRole: {+ some: {+ isTeamInitiator: true,+ sharedTeamRole: {+ teamId,+ },+ },+ },+ },+ select: {+ id: true,+ name: true,+ email: true,+ createdAt: true,+ avatar: true,+ },+ });++ return owner;+};++export const getTeamAdmins = async ({ teamId, ctx }: Transactional<{ teamId: string }>) => {+ const _tx = ctx?.tx ?? prisma;++ const admins = await _tx.user.findMany({+ where: {+ userTeamRole: {+ some: {+ sharedTeamRole: {+ isOwnerRole: true, // admins are on the same team role as the owner+ teamId,+ },+ },+ },+ },+ select: {+ id: true,+ email: true,+ },+ });++ return admins;+};++export const listTeamsM2M = async (options?: {+ pagination?: {+ page?: number;+ limit?: number;+ };+ emailSearchTerm?: string;+}) => {+ const whereClause = {+ ...(options?.emailSearchTerm+ ? {+ users: {+ some: {+ email: {+ contains: options.emailSearchTerm,+ },+ },+ },+ }+ : {}),+ };++ const teams = await prisma.team.findMany({+ ...includePagination(options?.pagination),++ where: whereClause,++ select: {+ id: true,+ name: true,+ createdAt: true,+ _count: {+ select: {+ users: true,+ aiAgents: true,+ },+ },+ users: {+ where: {+ userTeamRole: {+ some: {+ isTeamInitiator: true,+ },+ },+ },+ },+ subscription: {+ select: {+ id: true,+ status: true,+ properties: true,+ endDate: true,+ startDate: true,+ updatedAt: true,++ plan: {+ select: {+ id: true,+ name: true,+ price: true,+ stripeId: true,+ properties: true,+ isCustomPlan: true,+ priceId: true,+ isDefaultPlan: true,+ paid: true,+ description: true,+ },+ },+ },+ },+ },+ });++ teams.forEach(team => {+ if (team.subscription?.plan) {+ // eslint-disable-next-line no-param-reassign+ team.subscription.plan.properties = quotaUtils.fillPlanProps(team.subscription?.plan.properties as object) as any;+ // eslint-disable-next-line no-param-reassign+ team.subscription.properties = quotaUtils.fillSubscriptionProps(team.subscription.properties as object) as any;+ }+ });++ const count = await prisma.team.count({ where: whereClause });++ return {+ teams: teams.map(team => ({+ id: team.id,+ name: team.name,+ createdAt: team.createdAt,+ data: {+ users: team._count.users,+ aiAgents: team._count.aiAgents,+ },+ subscription: team.subscription,+ owner: team.users[0],+ })),++ count,+ };+};++export const getAllTeams = async (parentId: string, userId: number) => {+ try {+ // Use a single transaction for all database operations+ return await prisma.$transaction(+ async tx => {+ // 1. Get teams+ const teams = await tx.team.findMany({+ where: {+ OR: [{ id: parentId }, { parentId }],+ },+ select: {+ id: true,+ name: true,+ parentId: true,+ },+ });++ if (!teams.length) {+ return { teams: [] };+ }++ const teamIds = teams.map(team => team.id);++ // 2. Get all user team roles and user data in a single query+ const userTeamRoles = await tx.userTeamRole.findMany({+ where: {+ sharedTeamRole: {+ teamId: {+ in: teamIds,+ },+ },+ },+ select: {+ userId: true,+ roleId: true,+ isTeamInitiator: true,+ user: {+ select: {+ id: true,+ name: true,+ email: true,+ },+ },+ sharedTeamRole: {+ select: {+ teamId: true,+ name: true,+ canManageTeam: true,+ isOwnerRole: true,+ },+ },+ },+ });++ // 3. Get user settings in a single query+ const userIds = [...new Set(userTeamRoles.map(role => role.userId))];+ const userSettings = await tx.userSetting.findMany({+ where: {+ userId: {+ in: userIds,+ },+ settingKey: 'UserMarketingMetadata',+ },+ select: {+ userId: true,+ settingValue: true,+ settingKey: true,+ },+ });++ // 4. Create lookup maps for faster access+ const settingsByUserId = new Map();+ userSettings.forEach(setting => {+ if (!settingsByUserId.has(setting.userId)) {+ settingsByUserId.set(setting.userId, []);+ }+ settingsByUserId.get(setting.userId).push(setting);+ });++ const rolesByTeamId = new Map();+ userTeamRoles.forEach(role => {+ const teamId = role.sharedTeamRole.teamId;+ if (!rolesByTeamId.has(teamId)) {+ rolesByTeamId.set(teamId, []);+ }+ // Add settings to role+ const settings = settingsByUserId.get(role.userId) || [];+ rolesByTeamId.get(teamId).push({+ ...role,+ settings,+ });+ });++ // 5. Format final response using maps+ const formattedTeams = teams.map(team => ({+ ...team,+ users: rolesByTeamId.get(team.id) || [],+ }));++ return {+ teams: formattedTeams,+ };+ },+ {+ timeout: 15000, // 15 second timeout+ maxWait: 10000, // 10 second max wait+ },+ );+ } catch (error) {+ // Log the error for debugging+ LOGGER.error('Error in getAllTeams:', {+ error,+ parentId,+ userId,+ stack: error.stack,+ });++ if (error?.code === 'P2034') {+ // Prisma transaction timeout error code+ throw new ApiError(httpStatus.INTERNAL_SERVER_ERROR, 'Database operation timed out. Please try again.');+ }++ throw error;+ }+};diff --git a/packages/middleware/src/modules/team/validations/team.validation.ts b/packages/middleware/src/modules/team/validations/team.validation.tsnew file mode 100644index 00000000..49c7561b--- /dev/null+++ b/packages/middleware/src/modules/team/validations/team.validation.ts@@ -0,0 +1,201 @@+import Joi from 'joi';++const aclRuleSchema = Joi.object({+ access: Joi.string().required().allow(null).allow('').valid('r', 'rw', 'w'), // allow null and empty string (for no access)+ redirect: Joi.string().optional(),+ name: Joi.string().optional().allow(null).allow(''),+ internal: Joi.boolean().optional().allow(null).allow(''),+});++export const postTeamRole = {+ body: Joi.object({+ name: Joi.string().required(),+ canBeRemoved: Joi.boolean().optional().allow(null),+ canManageTeam: Joi.boolean().required(),+ acl: Joi.object({+ page: Joi.object()+ .pattern(+ Joi.string(), // for [key: string]+ aclRuleSchema, // for the rule structure+ )+ .required(),+ api: Joi.object()+ .pattern(+ Joi.string(), // for [key: string]+ aclRuleSchema, // for the rule structure+ )+ .required(),+ }),+ }),+};++export const deleteMember = {+ params: Joi.object({+ memberId: Joi.number().required(),+ }),+};++export const putTeamRole = {+ body: Joi.object({+ name: Joi.string().optional(),+ canBeRemoved: Joi.boolean().optional().allow(null),+ canManageTeam: Joi.boolean().optional(),+ acl: Joi.object({+ page: Joi.object()+ .pattern(+ Joi.string(), // for [key: string]+ aclRuleSchema, // for the rule structure+ )+ .required(),+ api: Joi.object()+ .pattern(+ Joi.string(), // for [key: string]+ aclRuleSchema, // for the rule structure+ )+ .required(),+ }),+ roleId: Joi.number().required(),+ }),+};+export const postTeam = {+ body: Joi.object({+ name: Joi.string().required(),+ }),+};++export const postTeamInvitation = {+ body: Joi.object({+ email: Joi.string().email().required(),+ roleId: Joi.number().required(),+ teamId: Joi.string().allow(null, '').optional(),+ spaceId: Joi.string().allow(null, '').optional(),+ agentId: Joi.string().allow(null, '').optional(),+ agentName: Joi.string().allow(null, '').optional(),+ }),+};++export const postTeamWithSubteamInvitation = {+ body: Joi.object({+ email: Joi.string().email().required(),+ roleId: Joi.number().required(),+ spaceId: Joi.string().allow(null, '').optional(),+ organizationId: Joi.string().allow(null, '').optional(),+ }),+};++export const postTeamShareAgentInvitation = {+ body: Joi.object({+ email: Joi.string().email().required(),+ agentId: Joi.string().allow(null, '').optional(),+ agentName: Joi.string().allow(null, '').optional(),+ }),+};++export const acceptTeamInvitation = {+ body: Joi.object({+ agentId: Joi.string().allow(null, '').optional(),+ addToSpaceId: Joi.string().allow(null, '').optional(),+ addToSpaceRoleId: Joi.number().allow(null).optional(),+ }),+ params: Joi.object({+ invitationId: Joi.string().required(),+ }),+};++export const deleteTeamInvitation = {+ params: Joi.object({+ invitationId: Joi.string().required(),+ }),+};++export const updateMemberRole = {+ body: Joi.object({+ userSpecificAcl: Joi.string().optional(),+ roleId: Joi.number().optional(),+ }),++ params: Joi.object({+ memberId: Joi.number().required(),+ }),+};++export const createSetting = {+ body: Joi.object({+ settingKey: Joi.string().required(),+ settingValue: Joi.string().required(),+ }),+};++export const getSetting = {+ params: Joi.object({+ settingKey: Joi.string().required(),+ }),+};++export const deleteSetting = {+ params: Joi.object({+ settingKey: Joi.string().required(),+ }),+};++export const getSettingsM2M = {+ params: Joi.object({+ teamId: Joi.string().required(),+ }),+};++export const getSettingM2M = {+ params: Joi.object({+ teamId: Joi.string().required(),+ settingKey: Joi.string().required(),+ }),+};++export const getTeamsM2M = {+ query: Joi.object({+ page: Joi.number().optional().default(1),+ limit: Joi.number().optional().default(10),+ email: Joi.string().optional(),+ }),+};++export const getTeamInfoM2M = {+ params: Joi.object({+ teamId: Joi.string().required(),+ }),+};++export const createSettingM2M = {+ params: Joi.object({+ teamId: Joi.string().required(),+ }),+ body: Joi.object({+ settingKey: Joi.string().required(),+ settingValue: Joi.string().required(),+ }),+};++export const deleteSettingM2M = {+ params: Joi.object({+ teamId: Joi.string().required(),+ settingKey: Joi.string().required(),+ }),+};++export const unassignMemberFromSubteam = {+ params: Joi.object({+ memberId: Joi.number().required(),+ subteamId: Joi.string().required(),+ }),+};++export const assignMemberToSubteam = {+ body: Joi.object({+ roleId: Joi.number().required(),+ notifyEmail: Joi.boolean().optional().default(true),+ }),+ params: Joi.object({+ memberId: Joi.number().required(),+ subteamId: Joi.string().required(),+ }),+};diff --git a/packages/middleware/src/modules/user/controllers/_sysapi/user.controller.m2m.ts b/packages/middleware/src/modules/user/controllers/_sysapi/user.controller.m2m.tsnew file mode 100644index 00000000..9cebd19f--- /dev/null+++ b/packages/middleware/src/modules/user/controllers/_sysapi/user.controller.m2m.ts@@ -0,0 +1,92 @@+import httpStatus from 'http-status';+import { ExpressHandlerWithParams } from '../../../../../types';+import { userService, userSettingsService } from '../../services';++import { UserSetting } from '@prisma/client';+import ApiError from '../../../../utils/apiError';++export const getSettings: ExpressHandlerWithParams<+ { userId: number },+ {},+ {+ settings: UserSetting[];+ }+> = async (req, res) => {+ const { userId } = req.params;+ const settings = await userSettingsService.getSettings(userId);+ return res.json({+ message: 'Settings retrieved successfully',+ settings,+ });+};++export const getSetting: ExpressHandlerWithParams<+ {+ settingKey: string;+ userId: number;+ },+ {},+ {+ setting: UserSetting;+ }+> = async (req, res) => {+ const { settingKey, userId } = req.params;+ const setting = await userSettingsService.getSetting(userId, settingKey);+ res.json({+ message: 'Setting retrieved successfully',+ setting,+ });+};++export const createSetting: ExpressHandlerWithParams<+ { userId: number },+ {+ settingKey: string;+ settingValue: string;+ },+ {+ setting: UserSetting;+ }+> = async (req, res) => {+ const { settingKey, settingValue } = req.body;+ const { userId } = req.params;+ const newSetting = await userSettingsService.createSetting(userId, settingKey, settingValue);+ res.json({+ message: 'Setting updated successfully',+ setting: newSetting,+ });+};++export const deleteSetting: ExpressHandlerWithParams<+ {+ settingKey: string;+ userId: number;+ },+ {},+ {}+> = async (req, res) => {+ const { settingKey } = req.params;+ const { userId } = req.params;+ const deletedSetting = await userSettingsService.deleteSetting(userId, settingKey);+ res.json({+ message: 'Setting deleted successfully',+ });+};++export const getUser: ExpressHandlerWithParams<+ { userId: number },+ {},+ {+ user: any;+ }+> = async (req, res) => {+ const { userId } = req.params;+ if (typeof userId !== 'number') {+ throw new ApiError(httpStatus.BAD_REQUEST, 'User ID must be a number');+ }+ const user = await userService.getUserInfoByIdM2M({ userId });+ res.json({+ message: 'User retrieved successfully',+ user,+ });+};diff --git a/packages/middleware/src/modules/user/controllers/user.controller.ts b/packages/middleware/src/modules/user/controllers/user.controller.tsnew file mode 100644index 00000000..4f156e17--- /dev/null+++ b/packages/middleware/src/modules/user/controllers/user.controller.ts@@ -0,0 +1,95 @@+import httpStatus from 'http-status';+import { ExpressHandler, ExpressHandlerWithParams } from '../../../../types';+import ApiError from '../../../utils/apiError';+import { authExpressHelpers } from '../../auth/helpers/auth-express.helper';+import { userSettingsService, userService } from '../services';+import { UserSetting } from '@prisma/client';++export const getUserInfo: ExpressHandler<+ {},+ {+ user: any;+ }+> = async (req, res) => {+ const userId = authExpressHelpers.getUserId(res);+ const teamId = authExpressHelpers.getTeamId(res);++ const tid = req.headers['x-affiliate-id'] as string | undefined;+ const refId = req.headers['x-referrer-id'] as string | undefined;++ const userInfo = await userService.getUserInfoById({ userId, teamId, referralHeaders: { tid, refId } });++ if (!userInfo) {+ throw new ApiError(httpStatus.NOT_FOUND, 'User not found');+ }++ res.json({+ message: 'User info retrieved successfully',+ user: userInfo,+ });+};++export const getSettings: ExpressHandler<+ {},+ {+ settings: UserSetting[];+ }+> = async (req, res) => {+ const userId = authExpressHelpers.getUserId(res);+ const settings = await userSettingsService.getSettings(userId);+ return res.json({+ message: 'Settings retrieved successfully',+ settings,+ });+};++export const getSetting: ExpressHandlerWithParams<+ {+ settingKey: string;+ },+ {},+ {+ setting: UserSetting;+ }+> = async (req, res) => {+ const userId = authExpressHelpers.getUserId(res);+ const { settingKey } = req.params;+ const setting = await userSettingsService.getSetting(userId, settingKey);+ res.json({+ message: 'Setting retrieved successfully',+ setting,+ });+};++export const createSetting: ExpressHandler<+ {+ settingKey: string;+ settingValue: string;+ },+ {+ setting: UserSetting;+ }+> = async (req, res) => {+ const userId = authExpressHelpers.getUserId(res);+ const { settingKey, settingValue } = req.body;+ const newSetting = await userSettingsService.createSetting(userId, settingKey, settingValue);+ res.json({+ message: 'Setting updated successfully',+ setting: newSetting,+ });+};++export const deleteSetting: ExpressHandlerWithParams<+ {+ settingKey: string;+ },+ {},+ {}+> = async (req, res) => {+ const userId = authExpressHelpers.getUserId(res);+ const { settingKey } = req.params;+ const deletedSetting = await userSettingsService.deleteSetting(userId, settingKey);+ res.json({+ message: 'Setting deleted successfully',+ });+};diff --git a/packages/middleware/src/modules/user/routes/_sysapi/index.ts b/packages/middleware/src/modules/user/routes/_sysapi/index.tsnew file mode 100644index 00000000..a672d164--- /dev/null+++ b/packages/middleware/src/modules/user/routes/_sysapi/index.ts@@ -0,0 +1,27 @@+import { Router } from 'express';+import asyncHandler from 'express-async-handler';+import * as userM2MController from '../../controllers/_sysapi/user.controller.m2m';+import { validate } from '../../../../middlewares/validate.middleware';+import * as userValidations from '../../validations/user.validation';+import {} from '../../../auth/middlewares/auth.middleware';++const router = Router();++router.get('/user/:userId', validate(userValidations.getUserM2M), asyncHandler(userM2MController.getUser));+router.get('/user/:userId/settings', validate(userValidations.getSettingsM2M), asyncHandler(userM2MController.getSettings));+router.get(+ '/user/:userId/settings/:settingKey',++ validate(userValidations.getSettingM2M),+ asyncHandler(userM2MController.getSetting),+);+router.put('/user/:userId/settings', validate(userValidations.createSettingM2M), asyncHandler(userM2MController.createSetting));++router.delete(+ '/user/:userId/settings/:settingKey',++ validate(userValidations.deleteSettingM2M),+ asyncHandler(userM2MController.deleteSetting),+);++export { router as _userRouter };diff --git a/packages/middleware/src/modules/user/routes/index.ts b/packages/middleware/src/modules/user/routes/index.tsnew file mode 100644index 00000000..8c8fb82a--- /dev/null+++ b/packages/middleware/src/modules/user/routes/index.ts@@ -0,0 +1,20 @@+import { Router } from 'express';+import asyncHandler from 'express-async-handler';+import * as userController from '../controllers/user.controller';+import { validate } from '../../../middlewares/validate.middleware';+import * as userValidations from '../validations/user.validation';+import { userAuthMiddleware } from '../../auth/middlewares/auth.middleware';++const router = Router();++// settings++router.get('/me', userAuthMiddleware, asyncHandler(userController.getUserInfo));++router.get('/settings', userAuthMiddleware, asyncHandler(userController.getSettings));+router.get('/settings/:settingKey', userAuthMiddleware, validate(userValidations.getSetting), asyncHandler(userController.getSetting));+router.put('/settings', userAuthMiddleware, validate(userValidations.createSetting), asyncHandler(userController.createSetting));++router.delete('/settings/:settingKey', userAuthMiddleware, validate(userValidations.deleteSetting), asyncHandler(userController.deleteSetting));++export { router as userRouter };diff --git a/packages/middleware/src/modules/user/services/index.ts b/packages/middleware/src/modules/user/services/index.tsnew file mode 100644index 00000000..511db7af--- /dev/null+++ b/packages/middleware/src/modules/user/services/index.ts@@ -0,0 +1,2 @@+export * as userService from './user.service';+export * as userSettingsService from './settings.user.service';diff --git a/packages/middleware/src/modules/user/services/settings.user.service.ts b/packages/middleware/src/modules/user/services/settings.user.service.tsnew file mode 100644index 00000000..35786255--- /dev/null+++ b/packages/middleware/src/modules/user/services/settings.user.service.ts@@ -0,0 +1,65 @@+import { UserSetting } from '@prisma/client';+import ApiError from '../../../utils/apiError';+import { prisma } from '../../../../prisma/prisma-client';++export async function getSettings(userId: number): Promise<UserSetting[]> {+ return prisma.userSetting.findMany({ where: { userId } });+}++export async function createSetting(userId: number, settingKey: string, settingValue: string): Promise<UserSetting> {+ const existingSetting = await prisma.userSetting.findFirst({+ where: {+ settingKey,+ userId,+ },+ });++ if (existingSetting) {+ return prisma.userSetting.update({+ where: {+ id: existingSetting.id,+ },+ data: {+ settingValue,+ },+ });+ }++ return prisma.userSetting.create({+ data: {+ user: { connect: { id: userId } },+ settingKey,+ settingValue,+ },+ });+}++export async function getSetting(userId: number, settingKey: string): Promise<UserSetting> {+ const setting = await prisma.userSetting.findFirst({+ where: {+ settingKey,+ userId,+ },+ });++ if (!setting) {+ throw new ApiError(404, 'Setting not found');+ }++ return setting;+}++export async function deleteSetting(userId: number, settingKey: string) {+ const deleted = await prisma.userSetting.deleteMany({+ where: {+ userId,+ settingKey,+ },+ });++ if (deleted.count === 0) {+ throw new ApiError(404, 'Setting not found');+ }++ return deleted;+}diff --git a/packages/middleware/src/modules/user/services/user.service.ts b/packages/middleware/src/modules/user/services/user.service.tsnew file mode 100644index 00000000..e0115622--- /dev/null+++ b/packages/middleware/src/modules/user/services/user.service.ts@@ -0,0 +1,347 @@+import httpStatus from 'http-status';+import { LOGGER } from '../../../../config/logging';+import { prisma } from '../../../../prisma/prisma-client';+import { PrismaTransaction, Transactional } from '../../../../types';+import ApiError from '../../../utils/apiError';+import * as quotaUtils from '../../quota/utils';++import { PRISMA_ERROR_CODES } from '../../../utils/general';+// import businessCustomMetrics from '../../../metrices/custom/business.custom.metrices';++export const syncUserDetails = async (+ dbUser: {+ id: number;+ email: string;+ teamId: string | null;+ avatar: string | null;+ name: string | null;+ },+ oauthData: {+ avatar?: string | null;+ name?: string | null;+ },+) => {+ // first, check if any of the user's details have changed+ const updateFields: any = {};++ if (dbUser.name !== oauthData.name) {+ updateFields.name = oauthData.name;+ }++ if (dbUser.avatar !== oauthData.avatar) {+ updateFields.avatar = oauthData.avatar;+ }++ // if all the details are up to date, return+ if (Object.keys(updateFields).length === 0) {+ return;+ }++ await prisma.user.update({+ where: {+ id: dbUser.id,+ },+ data: updateFields,+ });+};++export const getUserInfoById = async ({+ userId,+ teamId,+ referralHeaders,+ ctx,+}: Transactional<{+ userId: number;+ teamId: string;+ referralHeaders: {+ tid: string | undefined;+ refId: string | undefined;+ };+}>) => {+ const _tx = ctx?.tx ?? prisma;++ const user = await _tx.user.findUniqueOrThrow({+ where: {+ id: userId,+ },+ select: {+ id: true,+ email: true,+ avatar: true,+ name: true,+ createdAt: true,++ team: {+ select: {+ name: true,+ id: true,+ referredBy: true,+ parentId: true,+ },+ },++ userTeamRole: {+ select: {+ isTeamInitiator: true,+ userSpecificAcl: true,+ sharedTeamRole: {+ select: {+ canManageTeam: true,+ acl: true,+ name: true,+ id: true,++ team: {+ select: {+ name: true,+ id: true,+ parentId: true,+ referredBy: true,+ },+ },+ },+ },+ },+ },++ // teamMemberships: {+ // select: {+ // isTeamInitiator: true,+ // userSpecificAcl: true,+ // sharedTeamRole: {+ // select: {+ // canManageTeam: true,+ // acl: true,+ // name: true,+ // id: true,++ // team: {+ // select: {+ // name: true,+ // id: true,+ // parentId: true,+ // },+ // },+ // },+ // },+ // },+ // },+ },+ });++ // @ts-ignore+ user.roles = user.userTeamRole;+ // @ts-ignore+ user.team = user.userTeamRole.find(role => role.sharedTeamRole.team.id === teamId).sharedTeamRole.team;++ // @ts-ignore+ user.userTeamRole = user.userTeamRole.find(role => role.sharedTeamRole.team.id === teamId);+ // set the current team as the user's team++ return user;+};++export const getUserInfoByIdM2M = async ({ userId }: { userId: number }) => {+ const user = await prisma.user+ .findUniqueOrThrow({+ where: {+ id: userId,+ },+ select: {+ id: true,+ email: true,+ avatar: true,+ name: true,+ teamId: true,+ createdAt: true,+ updatedAt: true,+ },+ })+ .catch(err => {+ if (err.code === PRISMA_ERROR_CODES.NON_EXISTENT_RECORD) {+ throw new ApiError(httpStatus.NOT_FOUND, 'User not found');+ }++ throw err;+ });++ return user;+};++export const getUserByEmail = async ({ email, ctx }: Transactional<{ email: string }>) => {+ const _tx = ctx?.tx ?? prisma;++ const user = await _tx.user.findUnique({+ where: {+ email,+ },+ select: {+ id: true,+ email: true,+ teamId: true,+ avatar: true,+ name: true,+ },+ });++ return user;+};++export const createUserAndTeam = async ({ userInfo, ctx }: Transactional<{ userInfo: { email: string; name?: string; avatar?: string } }>) => {+ // create a new user and team++ const operations = async (tx: PrismaTransaction) => {+ let fullAccessPlan = await tx.plan.findFirst({+ where: {+ isDefaultPlan: true,+ },+ select: {+ id: true,+ },+ });++ if (!fullAccessPlan) {+ LOGGER.info(`Full Access PLAN DOESN'T EXIST. CREATING...`);+ fullAccessPlan = await tx.plan.create({+ data: {+ name: 'Full Access',+ price: 1,+ paid: true,+ isDefaultPlan: true,+ stripeId: 'na',+ priceId: 'na',+ properties: quotaUtils.buildDefaultPlanProps(),+ },+ select: {+ id: true,+ },+ });+ }++ const team = await tx.team.create({+ data: {+ name: userInfo.name ? `${userInfo.name}'s Team` : 'My Team',++ subscription: {+ create: {+ startDate: new Date(),+ stripeId: '',+ status: 'ACTIVE',+ plan: {+ connect: {+ id: fullAccessPlan.id,+ },+ },+ },+ },+ },+ select: {+ id: true,+ },+ });++ const userRecord = await tx.user.create({+ data: {+ email: userInfo.email,+ name: userInfo.name,+ avatar: userInfo.avatar,+ team: {+ connect: {+ id: team.id,+ },+ },+ },++ select: {+ id: true,+ email: true,+ teamId: true,+ avatar: true,+ name: true,+ },+ });++ await tx.userTeamRole.create({+ data: {+ isTeamInitiator: true,+ user: {+ connect: {+ id: userRecord.id,+ },+ },++ sharedTeamRole: {+ create: {+ name: 'Super Admin',+ isOwnerRole: true,+ canManageTeam: true,+ team: {+ connect: {+ id: team.id,+ },+ },+ },+ },+ },++ select: undefined,+ });++ return userRecord;+ };++ const user = await (ctx?.tx ? operations(ctx.tx) : prisma.$transaction(operations, { timeout: 10_000 }));++ // businessCustomMetrics.userSignupCounter.inc();++ return user;+};++export const findOrCreateUser = async ({ email, name, avatar }: { email: string; name?: string | null; avatar?: string | null }) => {+ let isNewUser = false;++ const user = await prisma.$transaction(+ async tx => {+ // const existingUser = await getUserByEmail({ email, ctx: { tx } });+ const existingUser = await tx.user.findUnique({+ where: {+ email,+ },+ select: {+ id: true,+ email: true,+ teamId: true,+ avatar: true,+ name: true,+ },+ });+ if (existingUser) {+ await syncUserDetails(existingUser, { name, avatar });+ return existingUser;+ }++ isNewUser = true;+ LOGGER.info(`USER ${email} DOESN'T EXIST. CREATING...`);+ const newRecord = await createUserAndTeam({+ userInfo: {+ email,+ name: name ?? undefined,+ avatar: avatar ?? undefined,+ },+ ctx: { tx },+ });++ return newRecord;+ },+ {+ timeout: 100_000, // take as much time as you need (CRITICAL TASK)+ },+ );++ // if (isNewUser) {+ // // send welcome email+ // const nameStr = name;+ // }++ return user;+};diff --git a/packages/middleware/src/modules/user/validations/user.validation.ts b/packages/middleware/src/modules/user/validations/user.validation.tsnew file mode 100644index 00000000..dc9e28fe--- /dev/null+++ b/packages/middleware/src/modules/user/validations/user.validation.ts@@ -0,0 +1,56 @@+import Joi from 'joi';++export const createSetting = {+ body: Joi.object({+ settingKey: Joi.string().required(),+ settingValue: Joi.string().required(),+ }),+};++export const getSetting = {+ params: Joi.object({+ settingKey: Joi.string().required(),+ }),+};++export const deleteSetting = {+ params: Joi.object({+ settingKey: Joi.string().required(),+ }),+};++export const createSettingM2M = {+ params: Joi.object({+ userId: Joi.number().required(),+ }),+ body: Joi.object({+ settingKey: Joi.string().required(),+ settingValue: Joi.string().required(),+ }),+};++export const getSettingM2M = {+ params: Joi.object({+ settingKey: Joi.string().required(),+ userId: Joi.number().required(),+ }),+};++export const deleteSettingM2M = {+ params: Joi.object({+ settingKey: Joi.string().required(),+ userId: Joi.number().required(),+ }),+};++export const getSettingsM2M = {+ params: Joi.object({+ userId: Joi.number().required(),+ }),+};++export const getUserM2M = {+ params: Joi.object({+ userId: Joi.alternatives().try(Joi.number(), Joi.string()).required(),+ }),+};diff --git a/packages/middleware/src/modules/vault/constants/vault.constants.ts b/packages/middleware/src/modules/vault/constants/vault.constants.tsnew file mode 100644index 00000000..7957a570--- /dev/null+++ b/packages/middleware/src/modules/vault/constants/vault.constants.ts@@ -0,0 +1,12 @@+export const vaultMessages = {+ SUCCESS_CREATE_SECRET: 'Successfully created secret',+ SUCCESS_DELETE_SECRET: 'Successfully deleted secret',+ SUCCESS_GET_ALL_SECRETS: 'Successfully get all secrets',+ SUCCESS_GET_SECRET_BY_ID: 'Successfully get secret by id',+ SUCCESS_UPDATE_SECRET_METADATA: 'Successfully updated secret metadata',+ SUCCESS_GET_ALL_SECRETS_COUNT: 'Successfully get all secrets count',+ ERROR_GENERATING_M2M_CLIENT_TOKEN: 'Something went wrong while generating M2M client token',+ ERROR_SECRET_NOT_FOUND: 'Secret not found',+ SUCCESS_SYNC_SECRETS: 'Successfully sync secrets',+ SUCCESS_GET_SECRET_BY_NAME: 'Successfully get secret by name',+}\ No newline at end of filediff --git a/packages/middleware/src/modules/vault/controllers/vault.controller.ts b/packages/middleware/src/modules/vault/controllers/vault.controller.tsnew file mode 100644index 00000000..bc9d65fa--- /dev/null+++ b/packages/middleware/src/modules/vault/controllers/vault.controller.ts@@ -0,0 +1,184 @@+import httpStatus from 'http-status';+import { ExpressHandler } from '../../../../types';+import * as vaultService from '../services/vault.service';++export const createVaultSecret: ExpressHandler<+ {+ teamId: string;+ secretId: string;+ key: string;+ value: string;+ metadata: string;+ },+ any+> = async (req, res) => {+ const { teamId, secretId, key, value, metadata } = req.body;++ try {+ const response = await vaultService.createSecret({+ teamId,+ secretId,+ key,+ value,+ metadata+ });+ return res.status(httpStatus.OK).json(response);+ } catch (error: any) {+ console.error('Failed to save secret for teamId: ', teamId, error.message);+ res.status(error?.statusCode || 500).json({ error: 'Failed to save secret.', message: error.message });+ }+};+++export const getAllSecrets: ExpressHandler<+ {+ teamId: string;+ userJWTToken: string;+ isM2MAccess: boolean;+ metadataFilter: string;+ },+ any+> = async (req, res) => {+ try {+ const { teamId } = req.params;+ const { metadataFilter } = req.query;+ const response = await vaultService.getAllSecrets(teamId, metadataFilter as string);+ return res.status(httpStatus.OK).json(response);++ } catch (error: any) {+ throw error;+ }+}++export const getSecretsCount: ExpressHandler<+ {+ teamId: string;+ userJWTToken: string;+ },+ any+> = async (req, res) => {+ const { teamId } = req.params;+ try {+ const response = await vaultService.getSecretsCount(+ teamId)+ return res.status(httpStatus.OK).json(response);+ } catch (error: any) {+ console.error('Failed to get secrets count: ', teamId, error.message);+ res.status(error?.statusCode || 500).json({ error: 'Failed to get secrets count', message: error.message });+ }+}++export const getSecretById: ExpressHandler<+ {+ teamId: string;+ secretId: string;+ },+ any+> = async (req, res) => {+ const { teamId, secretId } = req.params;+ try {+ const response = await vaultService.getSecretById(+ teamId, secretId)+ return res.status(httpStatus.OK).json(response);+ } catch (error: any) {+ console.error('Failed to get secrets count: ', teamId, error.message);+ res.status(error?.statusCode || 500).json({ error: 'Failed to get secrets count', message: error.message });+ }+}++export const checkSecretExistsById: ExpressHandler<+ {+ teamId: string;+ secretId: string;+ },+ any+> = async (req, res) => {+ const { teamId, secretId } = req.params;+ try {+ const response = await vaultService.checkSecretExistsById(+ teamId, secretId)+ return res.status(httpStatus.OK).json(response);+ } catch (error: any) {+ console.error('Failed to get secrets count: ', teamId, error.message);+ res.status(error?.statusCode || 500).json({ error: 'Failed to get secrets count', message: error.message });+ }+}++export const getSecretByName: ExpressHandler<+ {+ teamId: string;+ secretName: string;+ },+ any+> = async (req, res) => {+ const { teamId, secretName } = req.params;+ try {+ const response = await vaultService.getSecretByName(+ teamId, secretName)+ return res.status(httpStatus.OK).json(response);+ } catch (error: any) {+ console.error('Failed to get secrets count: ', teamId, error.message);+ res.status(error?.statusCode || 500).json({ error: 'Failed to get secrets count', message: error.message });+ }+}++export const checkSecretExistsByName: ExpressHandler<+ {+ teamId: string;+ secretName: string;+ },+ any+> = async (req, res) => {+ const { teamId, secretName } = req.params;+ const { excludeId } = req.query;+ try {+ const response = await vaultService.checkSecretExistsByName(+ teamId, secretName, excludeId as string)+ return res.status(httpStatus.OK).json(response);+ } catch (error: any) {+ console.error('Failed to get secrets count: ', teamId, error.message);+ res.status(error?.statusCode || 500).json({ error: 'Failed to get secrets count', message: error.message });+ }+}++export const deleteSecretById: ExpressHandler<+ {+ teamId: string;+ secretId: string;+ },+ any+> = async (req, res) => {+ const { teamId, secretId } = req.params;+ try {+ const response = await vaultService.deleteSecretById(+ teamId, secretId)+ return res.status(httpStatus.OK).json(response);+ } catch (error: any) {+ console.error('Failed to get secrets count: ', teamId, error.message);+ res.status(error?.statusCode || 500).json({ error: 'Failed to get secrets count', message: error.message });+ }+}++export const updateSecretMetadata: ExpressHandler<+ {+ teamId: string;+ secretId: string;+ metadata: any;+ },+ any+> = async (req, res) => {+ const { teamId, secretId } = req.params;+ const { metadata } = req.body;+ try {+ const response = await vaultService.updateSecretMetadata(+ {+ teamId,+ secretId,+ metadata+ })+ return res.status(httpStatus.OK).json(response);+ } catch (error: any) {+ console.error('Failed to get secrets count: ', teamId, error.message);+ res.status(error?.statusCode || 500).json({ error: 'Failed to get secrets count', message: error.message });+ }+}diff --git a/packages/middleware/src/modules/vault/routes/vault.route.ts b/packages/middleware/src/modules/vault/routes/vault.route.tsnew file mode 100644index 00000000..9bd3e26c--- /dev/null+++ b/packages/middleware/src/modules/vault/routes/vault.route.ts@@ -0,0 +1,58 @@+import { Router } from 'express';+import asyncHandler from 'express-async-handler';+import { validate } from '../../../middlewares/validate.middleware';+import { userAuthMiddleware } from '../../auth/middlewares/auth.middleware';+import * as vaultController from '../controllers/vault.controller';+import * as vaultValidations from '../validations/vault.validation';++const router = Router();++router.post('/secret',+ userAuthMiddleware,+ validate(vaultValidations.createVaultSecret),+ asyncHandler(vaultController.createVaultSecret),+);++router.get('/:teamId/secrets',+ userAuthMiddleware,+ asyncHandler(vaultController.getAllSecrets),+);++router.get(+ '/:teamId/count/secrets',+ userAuthMiddleware,+ asyncHandler(vaultController.getSecretsCount),+);++router.get('/:teamId/secrets/:secretId',+ userAuthMiddleware,+ asyncHandler(vaultController.getSecretById),+);++router.get('/:teamId/secrets/:secretId/exists',+ userAuthMiddleware,+ asyncHandler(vaultController.checkSecretExistsById),+);++router.get('/:teamId/secrets/name/:secretName',+ userAuthMiddleware,+ asyncHandler(vaultController.getSecretByName),+);++router.get('/:teamId/secrets/name/:secretName/exists',+ userAuthMiddleware,+ asyncHandler(vaultController.checkSecretExistsByName),+);++router.delete('/:teamId/secrets/:secretId',+ userAuthMiddleware,+ asyncHandler(vaultController.deleteSecretById),+);++router.put('/:teamId/secrets/:secretId/metadata',+ userAuthMiddleware,+ validate(vaultValidations.updateSecretMetadata),+ asyncHandler(vaultController.updateSecretMetadata),+);++export { router as vaultRouter };diff --git a/packages/middleware/src/modules/vault/services/vault.service.ts b/packages/middleware/src/modules/vault/services/vault.service.tsnew file mode 100644index 00000000..3e078a70--- /dev/null+++ b/packages/middleware/src/modules/vault/services/vault.service.ts@@ -0,0 +1,311 @@+import { ConnectorService, SRE } from '@smythos/sre';+import fs from 'fs';+import path from 'path';+import { config } from '../../../../config/config';+import { vaultMessages } from '../constants/vault.constants';++prepareSREConfigFiles();+process.env.SMYTH_PATH = config.variables.SRE_STORAGE_PATH; // needed for SRE initialization+SRE.init({+ Vault: {+ Connector: 'JSONFileVault',+ },+});++export function formatSecretData(secret, secretId) {+ let key = '';+ let value = '';+ for (const k in secret.data.data) {+ // since we only store single key in a path, so it will run only 1 time and fetch the key+ key = k;+ value = secret.data.data[k];+ }+ const metadata = {+ version: secret.data.metadata.version,+ created_time: secret.data.metadata.created_time,+ ...secret.data.metadata.custom_metadata,+ };++ return {+ id: secretId,+ key,+ value,+ metadata,+ };+}++export async function createSecret({ teamId, secretId, key, value, metadata }) {+ try {+ // create secret in JSON vault+ const vaultConnector = await getVaultConnector();+ let filePath = vaultConnector.vaultFile;++ const currentData = fs.readFileSync(filePath, 'utf8');+ const newData = JSON.parse(currentData || '{}');+ if (!newData[teamId]) {+ newData[teamId] = {};+ }+ newData[teamId][secretId] = value;+ fs.writeFileSync(filePath, JSON.stringify(newData));++ // Create metadata in JSON vault+ const metadataPath = getMetadataPath(filePath);+ const updatedMetadata = await setSecretMetadata(teamId, secretId, metadataPath, metadata);++ return {+ success: vaultMessages.SUCCESS_CREATE_SECRET,+ secret: {+ id: secretId,+ key,+ value,+ metadata: updatedMetadata,+ },+ };+ } catch (error: any) {+ console.error(error.message);+ throw error;+ }+}++export async function updateSecretMetadata({ teamId, secretId, metadata }) {+ try {+ const vaultConnector = await getVaultConnector();+ const secretFilePath = vaultConnector.vaultFile;+ const metadataFilePath = getMetadataPath(secretFilePath);++ const updatedMetadata = await setSecretMetadata(teamId, secretId, metadataFilePath, metadata);+ const secretData = await getSecretById(teamId, secretId);+ return {+ success: vaultMessages.SUCCESS_UPDATE_SECRET_METADATA,+ secret: {+ id: secretId,+ key: secretId,+ value: secretData.secret.value,+ metadata: updatedMetadata,+ },+ };+ } catch (error: any) {+ console.error(error.message);+ throw error;+ }+}++export async function getAllSecrets(teamId: string, metadataFilter: string = '') {+ try {+ const vaultConnector = await getVaultConnector();+ const allSecrets = await vaultConnector.team(teamId).listKeys();+ let secretsResponse = await Promise.all(allSecrets.map(secret => getSecret(teamId, secret)));+ let secrets = secretsResponse?.filter(secret => secret !== null);+ if (metadataFilter) {+ secrets = filterSecrets(secretsResponse, metadataFilter);+ }++ return { success: vaultMessages.SUCCESS_GET_ALL_SECRETS, secrets };+ } catch (error: any) {+ return { success: vaultMessages.SUCCESS_GET_ALL_SECRETS, secrets: [] };+ }+}++async function getSecretMetadata(teamId: string, secretId: string, metadataFilePath: string) {+ const metadataData = fs.readFileSync(metadataFilePath, 'utf8');+ const metadataNewData = JSON.parse(metadataData);+ return metadataNewData[teamId]?.[secretId] || {};+}++export async function getSecretById(teamId: string, secretId: string) {+ const secret = await getSecret(teamId, secretId);+ if (secret) {+ return {+ success: vaultMessages.SUCCESS_GET_SECRET_BY_ID,+ secret,+ };+ }+ return {+ error: vaultMessages.ERROR_SECRET_NOT_FOUND,+ secret: null,+ };+}++export async function checkSecretExistsById(teamId: string, secretId: string) {+ try {+ const existingSecret = await getSecret(teamId, secretId);+ return existingSecret ? true : false;+ } catch (error: any) {+ return false;+ }+}++export async function getSecretByName(teamId: string, secretName: string) {+ try {+ const secretData = await getSecretById(teamId, secretName);+ if (secretData.secret) {+ return {+ success: vaultMessages.SUCCESS_GET_SECRET_BY_NAME,+ secret: secretData.secret,+ };+ }+ return {+ error: vaultMessages.ERROR_SECRET_NOT_FOUND,+ secret: null,+ };+ } catch (error: any) {+ console.error(error.message);+ throw error;+ }+}++export async function checkSecretExistsByName(teamId: string, secretName: string, excludeId = null) {+ try {+ const existingSecretResponse = await getSecretByName(teamId, secretName);+ return existingSecretResponse.secret && existingSecretResponse.secret.id !== excludeId ? true : false;+ } catch (error: any) {+ return false;+ }+}++export async function deleteSecretById(teamId: string, secretId: string) {+ const vaultConnector = await getVaultConnector();+ const secretFilePath = vaultConnector.vaultFile;+ const metadataFilePath = getMetadataPath(secretFilePath);++ const currentData = fs.readFileSync(secretFilePath, 'utf8');+ const newData = JSON.parse(currentData);+ delete newData[teamId][secretId];+ fs.writeFileSync(secretFilePath, JSON.stringify(newData));++ await deleteSecretMetadata(teamId, secretId, metadataFilePath);+ return { success: vaultMessages.SUCCESS_DELETE_SECRET };+}++async function deleteSecretMetadata(teamId: string, secretId: string, metadataFilePath: string) {+ try {+ const metadataData = fs.readFileSync(metadataFilePath, 'utf8');+ const metadataNewData = JSON.parse(metadataData);+ delete metadataNewData[teamId][secretId];+ fs.writeFileSync(metadataFilePath, JSON.stringify(metadataNewData));+ return;+ } catch (error: any) {+ console.error(error.message);+ throw error;+ }+}++async function setSecretMetadata(teamId: string, secretId: string, metadataFilePath: string, metadata) {+ try {+ const updatedMetadata = {+ created_time: new Date().toISOString(),+ version: 1,+ ...metadata,+ };++ const metadataData = fs.readFileSync(metadataFilePath, 'utf8');+ const metadataNewData = JSON.parse(metadataData || '{}');+ if (!metadataNewData[teamId]) {+ metadataNewData[teamId] = {};+ }+ metadataNewData[teamId][secretId] = updatedMetadata;+ fs.writeFileSync(metadataFilePath, JSON.stringify(metadataNewData));++ return updatedMetadata;+ } catch (error: any) {+ console.error(error.message);+ throw error;+ }+}++export async function getSecretsCount(teamId: string) {+ try {+ const vaultConnector = await getVaultConnector();+ const allSecrets = await vaultConnector.team(teamId).listKeys();+ return { success: vaultMessages.SUCCESS_GET_ALL_SECRETS_COUNT, count: allSecrets.length };+ } catch (error: any) {+ console.error(error.message);+ throw error;+ }+}++async function getSecret(teamId: string, secretId: string) {+ try {+ const vaultConnector = await getVaultConnector();+ const secret = await vaultConnector.team(teamId).get(secretId);+ const metadataFilePath = getMetadataPath(vaultConnector.vaultFile);+ const metadata = await getSecretMetadata(teamId, secretId, metadataFilePath);+ return {+ id: secretId,+ key: secretId,+ value: secret,+ metadata,+ };+ } catch (error) {+ console.error(`Error getting secret ${secretId} for team ${teamId}`);+ return null;+ }+}++function filterSecrets(secrets, metadataFilter = '{}') {+ let filterObj = {};+ try {+ let metadatafilterObj = JSON.parse(metadataFilter);+ filterObj = { ...filterObj, ...metadatafilterObj };+ } catch (error) {}+ return secrets.filter(secret => {+ for (const key in filterObj) {+ if (secret.metadata[key] !== filterObj[key]) {+ return false;+ }+ }+ return true;+ });+}++function getMetadataPath(filePath: string) {+ const basePath = path.dirname(filePath);+ const metadataFilePath = path.join(basePath, 'vault-metadata.json');+ if (!fs.existsSync(metadataFilePath)) {+ fs.writeFileSync(metadataFilePath, '{}');+ }+ return metadataFilePath;+}++async function getVaultConnector() {+ const vaultConnector = ConnectorService.getVaultConnector();+ // let filePath = vaultConnector.vaultFile;+ // if (!filePath) {+ // throw new Error('Vault file path is not set');+ // }++ return vaultConnector;+}++function prepareSREConfigFiles() {+ // setup base dir for SRE+ const srePath = config.variables.SRE_STORAGE_PATH;+ if (!fs.existsSync(srePath)) {+ fs.mkdirSync(srePath, { recursive: true });+ }++ // setup base vault content+ const baseVaultContent = {+ development: {+ echo: '',+ openai: '$env(OPENAI_API_KEY)',+ anthropic: '',+ googleai: '',+ groq: '',+ togetherai: '',+ xai: '',+ deepseek: '',+ tavily: '',+ scrapfly: '',+ },+ };++ const vaultFilePath = path.join(config.variables.SRE_STORAGE_PATH, '.sre', 'vault.json');+ const dir = path.dirname(vaultFilePath);+ fs.mkdirSync(dir, { recursive: true });++ // Write the file+ if (!fs.existsSync(vaultFilePath)) {+ fs.writeFileSync(vaultFilePath, JSON.stringify(baseVaultContent, null, 2));+ }+}diff --git a/packages/middleware/src/modules/vault/validations/vault.validation.ts b/packages/middleware/src/modules/vault/validations/vault.validation.tsnew file mode 100644index 00000000..90ef839e--- /dev/null+++ b/packages/middleware/src/modules/vault/validations/vault.validation.ts@@ -0,0 +1,34 @@+import Joi from 'joi';++export const createVaultSecret = {+ body: Joi.object({+ teamId: Joi.string().alphanum().required(),+ secretId: Joi.string().required(),+ key: Joi.string()+ .required()+ .max(300),+ value: Joi.string().required().max(10000),+ metadata: Joi.object().optional()+ })+}++export const updateSecretMetadata = {+ body: Joi.object({+ metadata: Joi.object().required()+ })+}++export const syncVaultSecret = {+ body: Joi.object({+ teamId: Joi.string().alphanum().required(),+ secrets: Joi.array().items(Joi.object().keys({+ secretId: Joi.string().required(),+ key: Joi.string()+ .required()+ .max(300)+ ,+ value: Joi.string().required().max(10000),+ metadata: Joi.object().optional()+ })).required(),+ })+}\ No newline at end of filediff --git a/packages/middleware/src/routes/v1/_sysapi.ts b/packages/middleware/src/routes/v1/_sysapi.tsnew file mode 100644index 00000000..5a670575--- /dev/null+++ b/packages/middleware/src/routes/v1/_sysapi.ts@@ -0,0 +1,68 @@+import { Router } from 'express';+import { config } from '../../../config/config';+import { _aiAgentRouter } from '../../modules/ai-agent/routes/_sysapi';+import { _embodimentRouter } from '../../modules/embodiment/routes/_sysapi';+import { _teamRouter } from '../../modules/team/routes/_sysapi/team.route';++import { authMiddlewareFactory } from '../../modules/auth/middlewares/auth.middleware';+import { _domainRouter } from '../../modules/domains/routes/_sysapi/domain-registeration.route';+import { _subscriptionRouter } from '../../modules/subscription/routes/_sysapi/subscription.route.m2m';+import { _userRouter } from '../../modules/user/routes/_sysapi';++const mainRouter = Router();++type Route = {+ rootPath: string;+ route: Router;+ requireAuth?: boolean;+};++const defaultRoutes: Route[] = [+ {+ rootPath: '/',+ route: _aiAgentRouter,+ },+ {+ rootPath: '/',+ route: _teamRouter,+ },+ {+ rootPath: '/',+ route: _domainRouter,+ },+ {+ rootPath: '/',+ route: _embodimentRouter,+ },++ {+ rootPath: '/',+ route: _subscriptionRouter,+ },+ {+ rootPath: '/',+ route: _userRouter,+ },+];++const devRoutes: Route[] = [];++// PROTECT ALL SYSTEM ROUTES+mainRouter.use(+ authMiddlewareFactory({+ allowM2M: true,+ limitToM2M: true,+ }),+);++defaultRoutes.forEach(route => {+ mainRouter.use(route.rootPath, route.route);+});++if (config.variables.env === 'development') {+ devRoutes.forEach(route => {+ mainRouter.use(route.rootPath, route.route);+ });+}++export { mainRouter as systemRoutes };diff --git a/packages/middleware/src/routes/v1/index.ts b/packages/middleware/src/routes/v1/index.tsnew file mode 100644index 00000000..3ea81df1--- /dev/null+++ b/packages/middleware/src/routes/v1/index.ts@@ -0,0 +1,63 @@+import { Router } from 'express';+import { config } from '../../../config/config';+import { aiAgentRouter } from '../../modules/ai-agent/routes';+import { domainRouter } from '../../modules/domains/routes/domain-registeration.route';+import { embodimentRouter } from '../../modules/embodiment/routes';+import { subscriptionRouter } from '../../modules/subscription/routes/subscription.route';+import { teamRouter } from '../../modules/team/routes/team.route';+import { userRouter } from '../../modules/user/routes';++import { vaultRouter } from '../../modules/vault/routes/vault.route';++const mainRouter = Router();++type Route = {+ rootPath: string;+ route: Router;+ requireAuth?: boolean;+};++const defaultRoutes: Route[] = [+ {+ rootPath: '/user',+ route: userRouter,+ },+ {+ rootPath: '/',+ route: teamRouter,+ },+ {+ rootPath: '/',+ route: aiAgentRouter,+ },+ {+ rootPath: '/',+ route: domainRouter,+ },+ {+ rootPath: '/',+ route: embodimentRouter,+ },+ {+ rootPath: '/',+ route: subscriptionRouter,+ },+ {+ rootPath: '/vault',+ route: vaultRouter,+ },+];++const devRoutes: Route[] = [];++defaultRoutes.forEach(route => {+ mainRouter.use(route.rootPath, route.route);+});++if (config.variables.env === 'development') {+ devRoutes.forEach(route => {+ mainRouter.use(route.rootPath, route.route);+ });+}++export { mainRouter as routes };diff --git a/packages/middleware/src/scripts/_sys/_get_m2m_token.ts b/packages/middleware/src/scripts/_sys/_get_m2m_token.tsnew file mode 100644index 00000000..ff97a03a--- /dev/null+++ b/packages/middleware/src/scripts/_sys/_get_m2m_token.ts@@ -0,0 +1,6 @@+import { getM2MToken } from '../../../tests/utils/get-tokens';++(async () => {+ const token = await getM2MToken();+ console.log(token);+})();diff --git a/packages/middleware/src/scripts/package.json b/packages/middleware/src/scripts/package.jsonnew file mode 100644index 00000000..633b9a4c--- /dev/null+++ b/packages/middleware/src/scripts/package.json@@ -0,0 +1,11 @@+{+ "name": "smyth-middleware-scripts",+ "version": "1.3.2",+ "description": "",+ "main": "index.js",+ "scripts": {+ "script": "node -r esbuild-register"+ },+ "author": "",+ "license": "ISC"+}diff --git a/packages/middleware/src/utils/apiError.ts b/packages/middleware/src/utils/apiError.tsnew file mode 100644index 00000000..6779e08a--- /dev/null+++ b/packages/middleware/src/utils/apiError.ts@@ -0,0 +1,40 @@+/**+ * @class ApiError+ * @extends Error+ * @public+ * @description+ * ApiError class is used to create an error object that will be used by the error handler middleware.+ * It is the primary error class that will be used in the application.++ */+class ApiError extends Error {+ statusCode: number | null | undefined;++ isOperational: boolean;++ stack: string | undefined;++ errKey: string | undefined;++ isApiError: boolean;++ /**+ *+ * @param statusCode - http status code of the error+ * @param message - error message+ * @param isOperational - whether the error should be shown in production or not (if not, internal server error will be shown)+ * @param stack - error stack trace+ * @param errKey - error code to be used in the response+ */++ // eslint-disable-next-line default-param-last+ constructor(statusCode: number | null | undefined, message: string, errKey?: string, isOperational = true, stack?: string) {+ super(message);+ this.statusCode = statusCode;+ this.isOperational = isOperational === undefined ? true : isOperational;+ this.errKey = errKey;+ this.isApiError = true;+ }+}++export default ApiError;diff --git a/packages/middleware/src/utils/app-events.ts b/packages/middleware/src/utils/app-events.tsnew file mode 100644index 00000000..8c082a94--- /dev/null+++ b/packages/middleware/src/utils/app-events.ts@@ -0,0 +1,30 @@+import EventEmitter from 'events';+import { createLogger } from '../../config/logging-v2';++const LOGGER = createLogger('AppEvents');++interface AppEventsMap {+ STARTUP: undefined;+ SHUTDOWN: undefined;+}++class AppEvents extends EventEmitter {+ on<EventName extends keyof AppEventsMap>(event: EventName, listener: (payload: AppEventsMap[EventName]) => void): this {+ LOGGER.info(`APP EVENT EMITTED: ${event}`);+ try {+ super.on(event, listener);+ } catch (err) {+ //* catch errors so that the app doesn't crash+ LOGGER.error(`Error on event ${event}`, err);+ }+ return this;+ }++ emit<EventName extends keyof AppEventsMap>(event: EventName, payload: AppEventsMap[EventName]): boolean {+ return super.emit(event, payload);+ }+}++export const appEvents: AppEvents = new AppEvents();++appEvents.on('STARTUP', () => {});diff --git a/packages/middleware/src/utils/auth.ts b/packages/middleware/src/utils/auth.tsnew file mode 100644index 00000000..f831ab32--- /dev/null+++ b/packages/middleware/src/utils/auth.ts@@ -0,0 +1,6 @@+export const getFirstLastName = (trimmedName: string, trimmedUsername: string) => {+ const [firstName = '', lastName = '']: string[] =+ // eslint-disable-next-line no-unsafe-optional-chaining+ trimmedName || trimmedUsername ? (trimmedName || trimmedUsername)?.split(' ') : ['', ''];+ return [firstName, lastName];+};diff --git a/packages/middleware/src/utils/errorKeys.ts b/packages/middleware/src/utils/errorKeys.tsnew file mode 100644index 00000000..a344a720--- /dev/null+++ b/packages/middleware/src/utils/errorKeys.ts@@ -0,0 +1,11 @@+const errKeys = {+ AGENT_LOCK_FAIL: 'AGENT_LOCK_FAIL',+ TEAM_OWNER_ONLY_ACTION: 'TEAM_OWNER_ONLY_ACTION',+ HAS_ACTIVE_SUBSCRIPTION: 'HAS_ACTIVE_SUBSCRIPTION',+ NOT_ENOUGH_PERMISSIONS: 'NOT_ENOUGH_PERMISSIONS',+ UNAUTHORIZED_ACTION: 'UNAUTHORIZED_ACTION',+ PAID_ONLY_FEATURE: 'PAID_ONLY_FEATURE',+ NOT_ALLOWED_TO_ACCESS_AGENT: 'NOT_ALLOWED_TO_ACCESS_AGENT',+};++export default errKeys;diff --git a/packages/middleware/src/utils/general.ts b/packages/middleware/src/utils/general.tsnew file mode 100644index 00000000..17ccf850--- /dev/null+++ b/packages/middleware/src/utils/general.ts@@ -0,0 +1,102 @@+import path from 'path';+import { fileURLToPath } from 'url';+import { config } from '../../config/config';+import axios from 'axios';+import fs from 'fs/promises';++export function includePagination(pagination?: { page?: string | number; limit?: string | number }): {+ skip?: number;+ take?: number;+} {+ if (!pagination || !pagination?.page || !pagination?.limit) {+ return {};+ }+ let { page, limit } = pagination;++ page = parseInt(page as string, 10);+ limit = parseInt(limit as string, 10);++ const skip = (page - 1) * limit;+ return {+ skip,+ take: limit,+ };+}++export const stringifyErr = (err: any) => {+ try {+ return JSON.stringify(err);+ } catch (error) {+ return err;+ }+};++export const getFilename = () => {+ return fileURLToPath(import.meta.url);+};++export const getDirname = () => {+ return path.dirname(getFilename());+};++export function convertToOriginalType(value: any) {+ // If the value is already a number, boolean, or object, return it as is+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'object') {+ return value;+ }++ // If the value is not a string, return it as is+ if (typeof value !== 'string') {+ return value;+ }++ // Check for boolean values in string+ if (value.toLowerCase() === 'true') return true;+ if (value.toLowerCase() === 'false') return false;++ // Check for number values in string+ if (/^-?\d+\.?\d*$/.test(value)) return Number(value);++ // Check for JSON objects/arrays in string+ try {+ const parsed = JSON.parse(value);+ if (typeof parsed === 'object' && parsed !== null) return parsed;+ } catch (e) {+ // Not a JSON string+ }++ // Return the original string+ return value;+}++export const getTimestampIn000Utc = (date?: Date) => {+ const dateNow = date || new Date();++ // Convert to UTC and set hours, minutes, seconds, and milliseconds to 0+ dateNow.setUTCHours(0, 0, 0, 0);+ return dateNow.getTime();+};++export const getUtcStartOfDayStr = (date?: Date) => {+ const dateNow = date || new Date();+ dateNow.setUTCHours(0, 0, 0, 0);+ return dateNow.toISOString();+};++export const PRISMA_ERROR_CODES = {+ UNIQUE_CONSTRAINT: 'P2002',+ FOREIGN_KEY_CONSTRAINT: 'P2003',+ NON_EXISTENT_RECORD: 'P2025',+};++export const dirExists = async (path: string): Promise<boolean> => {+ try {+ const stat = await fs.stat(path);+ return stat.isDirectory();+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'ENOENT') {+ return false; // directory does not exist+ }+ throw err; // rethrow other errors+ }+};diff --git a/packages/middleware/src/utils/index.ts b/packages/middleware/src/utils/index.tsnew file mode 100644index 00000000..2f004d5a--- /dev/null+++ b/packages/middleware/src/utils/index.ts@@ -0,0 +1 @@+export * as versionUtils from './versions';diff --git a/packages/middleware/src/utils/lib.ts b/packages/middleware/src/utils/lib.tsnew file mode 100644index 00000000..38b00e00--- /dev/null+++ b/packages/middleware/src/utils/lib.ts@@ -0,0 +1,6 @@+import { config } from '../../config/config';+import axios from 'axios';++export const crawlerAxiosInstance = axios.create({+ baseURL: config.variables.SMYTH_CRAWLER,+});diff --git a/packages/middleware/src/utils/models.ts b/packages/middleware/src/utils/models.tsnew file mode 100644index 00000000..b329db54--- /dev/null+++ b/packages/middleware/src/utils/models.ts@@ -0,0 +1 @@+export * from '@prisma/client';diff --git a/packages/middleware/src/utils/pick.ts b/packages/middleware/src/utils/pick.tsnew file mode 100644index 00000000..7097c18a--- /dev/null+++ b/packages/middleware/src/utils/pick.ts@@ -0,0 +1,21 @@+/**+ * Create an object composed of the picked object properties+ * @param {Object} object+ * @param {string[]} keys+ * @returns {Object}+ */++type AnyObject = {+ [x: string]: any;+};++const pick = (object: AnyObject, keys: string[]) =>+ keys.reduce((newObject: AnyObject, key) => {+ if (object && Object.prototype.hasOwnProperty.call(object, key)) {+ // eslint-disable-next-line no-param-reassign+ newObject[key] = object[key];+ }+ return newObject;+ }, {});++export { pick };diff --git a/packages/middleware/src/utils/versions.ts b/packages/middleware/src/utils/versions.tsnew file mode 100644index 00000000..83ae923d--- /dev/null+++ b/packages/middleware/src/utils/versions.ts@@ -0,0 +1,18 @@+import httpStatus from 'http-status';+import ApiError from './apiError';++export const extractVersionComponents = (version: string) => {+ // example version: '1.1', '1.2'+ const matchRegex = /^\d+\.\d+$/;+ if (!matchRegex.test(version)) {+ throw new ApiError(httpStatus.BAD_REQUEST, `Invalid version: ${version}`);+ }+ const versionComponents = version.split('.');+ const major = Number(versionComponents[0]);+ const minor = Number(versionComponents[1]);+ return { major, minor };+};++export const buildUnformattedVersion = ({ major, minor }: { major: number; minor: number }) => {+ return `${major}.${minor}`;+};diff --git a/packages/middleware/src/views/emails/subscription-cancellation-scheduled.ejs b/packages/middleware/src/views/emails/subscription-cancellation-scheduled.ejsnew file mode 100644index 00000000..6b440737--- /dev/null+++ b/packages/middleware/src/views/emails/subscription-cancellation-scheduled.ejs@@ -0,0 +1,115 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Plan Cancellation</title>+ <style type="text/css">+ body {+ margin: 0;+ padding: 0;+ background-color: #f2f2f2;+ font-family: 'Inter', Arial, sans-serif;+ }+ .container {+ width: 100%;+ max-width: 600px;+ background-color: #ffffff;+ margin: 0 auto;+ padding: 20px;+ text-align: center;+ border-collapse: collapse;+ }+ .logo img{+ background-color: #ffffff;+ width: 150px;+ height: auto;+ padding: 20px;+ }+ .content {+ padding: 20px 20px;+ color: #1d1d1d;+ }+ .content h2 {+ color: #2AAD8E;+ }+ .content h3 {+ color: #1d1d1d;+ }+ .content h4 {+ color: #1d1d1d;+ }+ .button {+ background-color: #2AAD8E;+ color: white;+ padding: 10px 20px;+ text-decoration: none;+ display: inline-block;+ margin: 10px 10px;+ border-radius: 5px;+ }+ .footer {+ font-size: 12px;+ color: #1d1d1d;+ padding: 20px;+ }+ .social-icons img {+ width: 24px;+ height: auto;+ margin: 0 5px;+ }++ /* Responsive styles */+ @media only screen and (max-width: 620px) {+ .container {+ width: 100%;+ padding: 10px;+ }+ .logo img {+ width: 100px; /* Adjust based on your logo size */+ }+ .button {+ width: 100%;+ padding: 15px 0;+ }+ .social-icons img {+ width: 20px;+ }+ }+ </style>+</head>+<body>+ <div class="container">+ <div class="logo">+ <!-- Include your logo image here -->+ <img src="https://app.smythos.dev/img/smythos-logo.png" alt="SmythOS Logo" />+ </div>+ <div class="content">+ <h2>We Will Miss You ☹️</h2>+ <p>This email is to confirm that your subscription has been cancelled. Your plan will remain active until the end of your current billing period, which is on <strong><%= subs.periodEnd %></strong>.</p>+ <p>After the said date, your account will revert to our default plan and you will lose access to all your <strong><%= subs.product.name %></strong> plan's privileges.</p>+ <p>In case you change your mind and want to pick up where you left off, you may restart your plan or select a new premium plan.</p><b>+ <p><a href="<%= config.FRONTEND_BASE_URL %>/my-plan" class="button">Restart Subscription</a> <a href="<%= config.FRONTEND_BASE_URL %>/my-plan" class="button">Explore Other Plans</a>+ </div>+ <div class="footer">+ <div class="social-icons">+ <!-- Include your LinkedIn and Discord icons here -->+ <p>Join our community:</p>+ <a href="https://www.linkedin.com/company/smythos/mycompany/" target="_blank">+ <!-- <img src="path-to-linkedin-icon.png" alt="LinkedIn" /> -->+ </a>+ <a href="https://discord.gg/pF8GSzbBEM" target="_blank">+ <!-- <img src="path-to-discord-icon.png" alt="Discord" /> -->+ Discord+ </a>+ </div>+ <div>+ <a href="mailto:[email protected]">Contact Us</a>+ </div>+ <p>© 2024 SmythOS an INK Content, Inc. company • 1321 Upland Dr. 1036 • Houston, TX 77339</p>+ <a href="https://smythos.com" target="_blank">www.smythos.com</a>+ </div>+ </div>+</body>+</html>diff --git a/packages/middleware/src/views/emails/subscription-created.ejs b/packages/middleware/src/views/emails/subscription-created.ejsnew file mode 100644index 00000000..ff21d7e2--- /dev/null+++ b/packages/middleware/src/views/emails/subscription-created.ejs@@ -0,0 +1,116 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Buy Plan - Successful</title>+ <style type="text/css">+ body {+ margin: 0;+ padding: 0;+ background-color: #f2f2f2;+ font-family: 'Inter', Arial, sans-serif;+ }+ .container {+ width: 100%;+ max-width: 600px;+ background-color: #ffffff;+ margin: 0 auto;+ padding: 20px 20px;+ text-align: center;+ border-collapse: collapse;+ }+ .logo img {+ background-color: #ffffff;+ width: 150px;+ height: auto;+ padding: 20px;+ }+ .content {+ padding: 20px 20px;+ color: #1d1d1d;+ }+ .content h2 {+ color: #2aad8e;+ }+ .button {+ background-color: #2aad8e;+ color: white;+ padding: 10px 20px;+ text-decoration: none;+ display: inline-block;+ margin: 20px 0;+ border-radius: 5px;+ }+ .footer {+ font-size: 12px;+ color: #1d1d1d;+ padding: 20px;+ }+ .social-icons img {+ width: 24px;+ height: auto;+ margin: 0 5px;+ }++ /* Responsive styles */+ @media only screen and (max-width: 620px) {+ .container {+ width: 100%;+ padding: 10px;+ }+ .logo img {+ width: 100px; /* Adjust based on your logo size */+ }+ .button {+ width: 100%;+ padding: 15px 0;+ }+ .social-icons img {+ width: 20px;+ }+ }+ </style>+ </head>+ <body>+ <div class="container">+ <div class="logo">+ <!-- Include your logo image here -->+ <img src="https://app.smythos.dev/img/smythos-logo.png" alt="SmythOS Logo" />+ </div>+ <div class="content">+ <h2>Confirmation of SmythOS Purchase</h2>+ <p>+ Thank you for your recent purchase of the <strong style="color: #2aad8e; font-weight: bold">SmythOS</strong>+ <strong> <%= plan.name %> </strong> plan! We are delighted you have chosen us to streamline your business processes.+ </p>+ <p>+ Your plan provides you access to our <strong>Smyth Agent Studio</strong>, allowing you to build AI agents with enterprise integrations and+ get priority support to generate efficiencies across your organization.+ </p>+ <p>Let's start your agent building journey now!</p>+ <a href="<%= config.FRONTEND_BASE_URL %>" target="_blank" class="button">Go to Agent Studio</a>+ </div>+ <div class="footer">+ <p>Join our community:</p>+ <div class="social-icons">+ <!-- Include your LinkedIn and Discord icons here -->+ <a href="https://www.linkedin.com/company/smythos/mycompany/" target="_blank">+ <!-- <img src="path-to-linkedin-icon.png" alt="LinkedIn" /> -->+ </a>+ <a href="https://discord.gg/pF8GSzbBEM" target="_blank">+ <!-- <img src="path-to-discord-icon.png" alt="Discord" /> -->+ Discord+ </a>+ </div>+ <div>+ <!-- <a href="{{ unsubscribe_link_all }}">Unsubscribe</a> | -->+ <a href="mailto:[email protected]">Contact Us</a>+ </div>+ <p>© 2024 SmythOS an INK Content, Inc. company • 1321 Upland Dr. 1036 • Houston, TX 77339</p>+ <a href="https://smythos.com" target="_blank">www.smythos.com</a>+ </div>+ </div>+ </body>+</html>diff --git a/packages/middleware/src/views/emails/successful-team-join.ejs b/packages/middleware/src/views/emails/successful-team-join.ejsnew file mode 100644index 00000000..dd376694--- /dev/null+++ b/packages/middleware/src/views/emails/successful-team-join.ejs@@ -0,0 +1,115 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Welcome to Your Team</title>+ <style type="text/css">+ body {+ margin: 0;+ padding: 0;+ background-color: #f2f2f2;+ font-family: 'Inter', Arial, sans-serif;+ }+ .container {+ width: 100%;+ max-width: 600px;+ background-color: #ffffff;+ margin: 0 auto;+ padding: 20px;+ text-align: center;+ border-collapse: collapse;+ }+ .logo img{+ background-color: #ffffff;+ width: 150px;+ height: auto;+ padding: 20px;+ }+ .content {+ padding: 20px 20px;+ color: #1d1d1d;+ }+ .content h2 {+ color: #2AAD8E;+ }+ .content h3 {+ color: #1d1d1d;+ }+ .content h4 {+ color: #1d1d1d;+ }+ .button {+ background-color: #2AAD8E;+ color: white;+ padding: 10px 20px;+ text-decoration: none;+ display: inline-block;+ margin: 20px 0;+ border-radius: 5px;+ }+ .footer {+ font-size: 12px;+ color: #1d1d1d;+ padding: 20px;+ }+ .social-icons img {+ width: 24px;+ height: auto;+ margin: 0 5px;+ }++ /* Responsive styles */+ @media only screen and (max-width: 620px) {+ .container {+ width: 100%;+ padding: 10px;+ }+ .logo img {+ width: 100px; /* Adjust based on your logo size */+ }+ .button {+ width: 100%;+ padding: 15px 0;+ }+ .social-icons img {+ width: 20px;+ }+ }+ </style>+</head>+<body>+ <div class="container">+ <div class="logo">+ <!-- Include your logo image here -->+ <img src="https://app.smythos.dev/img/smythos-logo.png" alt="SmythOS Logo" />+ </div>+ <div class="content">+ <h2>It's Official!</h2>+ <p>You're in! This message is to confirm that you have successfully joined <strong><%= inviter.name %>'s</strong> <strong style="color: #2AAD8E; font-weight: bold;"><%= team.name %> team</strong>.</p>+ <a href="<%= config.FRONTEND_BASE_URL %>" class="button">Go to Agent Studio</a>+ <p>Now that you're officially part of <%= inviter.name %>'s team, you'll be able to collaborate with your team members. Your role and permissions will be defined by your team admin.</p>+ <p>We're excited to see what powerful AI agents you'll build with your team!</p>+ </div>+ <div class="footer">+ <div class="social-icons">+ <!-- Include your LinkedIn and Discord icons here -->+ <p>Join our community:</p>+ <a href="https://www.linkedin.com/company/smythos/mycompany/" target="_blank">+ <!-- <img src="path-to-linkedin-icon.png" alt="LinkedIn" /> -->+ </a>+ <a href="https://discord.gg/pF8GSzbBEM" target="_blank">+ <!-- <img src="path-to-discord-icon.png" alt="Discord" /> -->+ Discord+ </a>+ </div>+ <div>+ <a href="mailto:[email protected]">Contact Us</a>+ </div>+ <p>© 2024 SmythOS an INK Content, Inc. company • 1321 Upland Dr. 1036 • Houston, TX 77339</p>+ <a href="https://smythos.com" target="_blank">www.smythos.com</a>+ </div>+ </div>+</body>+</html>diff --git a/packages/middleware/src/views/emails/team-invitation-accepted.ejs b/packages/middleware/src/views/emails/team-invitation-accepted.ejsnew file mode 100644index 00000000..5eeddad3--- /dev/null+++ b/packages/middleware/src/views/emails/team-invitation-accepted.ejs@@ -0,0 +1,117 @@+<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Team Invitation Accepted</title>+ <style type="text/css">+ body {+ margin: 0;+ padding: 0;+ background-color: #f2f2f2;+ font-family: 'Inter', Arial, sans-serif;+ }+ .container {+ width: 100%;+ max-width: 600px;+ background-color: #ffffff;+ margin: 0 auto;+ padding: 20px;+ text-align: center;+ border-collapse: collapse;+ }+ .logo img {+ background-color: #ffffff;+ width: 150px;+ height: auto;+ padding: 20px;+ }+ .content {+ padding: 20px 20px;+ color: #1d1d1d;+ }+ .content h2 {+ color: #2aad8e;+ }+ .content h3 {+ color: #1d1d1d;+ }+ .content h4 {+ color: #1d1d1d;+ }+ .button {+ background-color: #2aad8e;+ color: white;+ padding: 10px 20px;+ text-decoration: none;+ display: inline-block;+ margin: 20px 0;+ border-radius: 5px;+ }+ .footer {+ font-size: 12px;+ color: #1d1d1d;+ padding: 20px;+ }+ .social-icons img {+ width: 24px;+ height: auto;+ margin: 0 5px;+ }++ /* Responsive styles */+ @media only screen and (max-width: 620px) {+ .container {+ width: 100%;+ padding: 10px;+ }+ .header img {+ width: 100px; /* Adjust based on your logo size */+ }+ .button {+ width: 100%;+ padding: 15px 0;+ }+ .social-icons img {+ width: 20px;+ }+ }+ </style>+ </head>+ <body>+ <div class="container">+ <div class="logo">+ <!-- Include your logo image here -->+ <img src="https://app.smythos.dev/img/smythos-logo.png" alt="SmythOS Logo" />+ </div>+ <div class="content">+ <h2>Better Together</h2>+ <p>+ This is to confirm that <strong><%= invitee.name || invitee.email %></strong> has accepted your invitation to join+ <strong style="color: #2aad8e; font-weight: bold"><%= team.name %> team</strong>.+ </p>+ <p>Want to invite more members to your team?</p>+ <a href="<%= config.FRONTEND_BASE_URL %>/teams/members" class="button">Send Another Invitation</a>+ </div>+ <div class="footer">+ <div class="social-icons">+ <!-- Include your LinkedIn and Discord icons here -->+ <p>Join our community:</p>+ <a href="https://www.linkedin.com/company/smythos/mycompany/" target="_blank">+ <!-- <img src="path-to-linkedin-icon.png" alt="LinkedIn" /> -->+ </a>+ <a href="https://discord.gg/pF8GSzbBEM" target="_blank">+ <!-- <img src="path-to-discord-icon.png" alt="Discord" /> -->+ Discord+ </a>+ </div>+ <div>+ <a href="mailto:[email protected]">Contact Us</a>+ </div>+ <p>© 2024 SmythOS an INK Content, Inc. company • 1321 Upland Dr. 1036 • Houston, TX 77339</p>+ <a href="https://smythos.com" target="_blank">www.smythos.com</a>+ </div>+ </div>+ </body>+</html>diff --git a/packages/middleware/src/views/emails/team-invitation-sent.ejs b/packages/middleware/src/views/emails/team-invitation-sent.ejsnew file mode 100644index 00000000..8f873d1d--- /dev/null+++ b/packages/middleware/src/views/emails/team-invitation-sent.ejs@@ -0,0 +1,118 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Team Invite</title>+ <style type="text/css">+ body {+ margin: 0;+ padding: 0;+ background-color: #f2f2f2;+ font-family: 'Inter', Arial, sans-serif;+ }+ .container {+ width: 100%;+ max-width: 600px;+ background-color: #ffffff;+ margin: 0 auto;+ padding: 20px 20px;+ text-align: center;+ border-collapse: collapse;+ }+ .logo img{+ background-color: #ffffff;+ width: 150px;+ height: auto;+ padding: 20px;+ }+ .content {+ padding: 20px 20px;+ color: #1d1d1d;+ }+ .content h2 {+ color: #2AAD8E;+ }+ .content h3 {+ color: #1d1d1d;+ }+ .content h4 {+ color: #1d1d1d;+ }+ .button {+ background-color: #2AAD8E;+ color: white;+ padding: 10px 20px;+ text-decoration: none;+ display: inline-block;+ margin: 20px 0;+ border-radius: 5px;+ }+ .footer {+ font-size: 12px;+ color: #1d1d1d;+ padding: 20px;+ }+ .social-icons img {+ width: 24px;+ height: auto;+ margin: 0 5px;+ }++ /* Responsive styles */+ @media only screen and (max-width: 620px) {+ .container {+ width: 100%;+ padding: 10px;+ }+ .logo img {+ width: 100px; /* Adjust based on your logo size */+ }+ .button {+ width: 100%;+ padding: 15px 0;+ }+ .social-icons img {+ width: 20px;+ }+ }+ </style>+</head>+<body>+ <div class="container">+ <div class="logo">+ <!-- Include your logo image here -->+ <img src="https://app.smythos.dev/img/smythos-logo.png" alt="SmythOS Logo">+ </div>+ <div class="content">+ <h2>Ready to Join a Winning Team?</h2>+ <h3>Congratulations<% if (invitee?.name) { %>, <%= invitee.name %><% } %>!</h3>+ <p>Here is your exclusive invitation<% if (inviter?.name) { %> from <strong><%= inviter.name %></strong><% } %> to join <strong style="color: #2AAD8E; font-weight: bold;"><%= team?.name %> team</strong>.</p>+ <p>Don't miss the opportunity to collaborate and build powerful AI agents together with a team.</p>+ <h4>⏰👇Accept your invitation before it expires!</h4>+ <a href="<%= config.FRONTEND_BASE_URL %>/teams/accept-invitation/<%= invitation.code %>" class="button">Accept Team Invite</a>+ <p>Once you accept, you'll be officially part of the team and be able to collaborate with your team members. Your role and permissions will be defined by your team admin.</p>+ <p>We're excited to see what powerful AI agents you'll build with your team!</p>+ </div>+ <div class="footer">+ <p>Join our community:</p>+ <div class="social-icons">+ <!-- Include your LinkedIn and Discord icons here -->+ <a href="https://www.linkedin.com/company/smythos/mycompany/" target="_blank">+ <!-- <img src="path-to-linkedin-icon.png" alt="LinkedIn" /> -->+ </a>+ <a href="https://discord.gg/pF8GSzbBEM" target="_blank">+ <!-- <img src="path-to-discord-icon.png" alt="Discord" /> -->+ Discord+ </a>+ </div>+ <div>+ <a href="mailto:[email protected]">Contact Us</a>+ </div>+ <p>© 2024 SmythOS an INK Content, Inc. company • 1321 Upland Dr. 1036 • Houston, TX 77339</p>+ <a href="https://smythos.com" target="_blank">www.smythos.com</a>+ </div>+ </div>+</body>+</html>diff --git a/packages/middleware/src/views/emails/upcoming-subscription-renewal.ejs b/packages/middleware/src/views/emails/upcoming-subscription-renewal.ejsnew file mode 100644index 00000000..4f6af0d2--- /dev/null+++ b/packages/middleware/src/views/emails/upcoming-subscription-renewal.ejs@@ -0,0 +1,114 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Subscription Renewal</title>+ <style type="text/css">+ body {+ margin: 0;+ padding: 0;+ background-color: #f2f2f2;+ font-family: 'Inter', Arial, sans-serif;+ }+ .container {+ width: 100%;+ max-width: 600px;+ background-color: #ffffff;+ margin: 0 auto;+ padding: 20px;+ text-align: center;+ border-collapse: collapse;+ }+ .logo img{+ background-color: #ffffff;+ width: 150px;+ height: auto;+ padding: 20px;+ }+ .content {+ padding: 20px 20px;+ color: #1d1d1d;+ }+ .content h2 {+ color: #2AAD8E;+ }+ .content h3 {+ color: #1d1d1d;+ }+ .content h4 {+ color: #1d1d1d;+ }+ .button {+ background-color: #2AAD8E;+ color: white;+ padding: 10px 20px;+ text-decoration: none;+ display: inline-block;+ margin: 20px 0;+ border-radius: 5px;+ }+ .footer {+ font-size: 12px;+ color: #1d1d1d;+ padding: 20px;+ }+ .social-icons img {+ width: 24px;+ height: auto;+ margin: 0 5px;+ }++ /* Responsive styles */+ @media only screen and (max-width: 620px) {+ .container {+ width: 100%;+ padding: 10px;+ }+ .logo img {+ width: 100px; /* Adjust based on your logo size */+ }+ .button {+ width: 100%;+ padding: 15px 0;+ }+ .social-icons img {+ width: 20px;+ }+ }+ </style>+</head>+<body>+ <div class="container">+ <div class="logo">+ <!-- Include your logo image here -->+ <img src="https://app.smythos.dev/img/smythos-logo.png" alt="SmythOS Logo" />+ </div>+ <div class="content">+ <h2>Your Subscription is Due for Renewal</h2>+ <p>This is a quick reminder that your subscription is up for renewal on <strong>{{renewalDate}}</strong> and your card on file will be charged automatically on the said date.</p>+ <p>Please ensure that your account is up-to-date to prevent usage interruptions.</p>+ <a href="<%= config.FRONTEND_BASE_URL %>/my-plan" class="button">Check Billing Account</a>+ </div>+ <div class="footer">+ <div class="social-icons">+ <!-- Include your LinkedIn and Discord icons here -->+ <p>Join our community:</p>+ <a href="https://www.linkedin.com/company/smythos/mycompany/" target="_blank">+ <!-- <img src="path-to-linkedin-icon.png" alt="LinkedIn" /> -->+ </a>+ <a href="https://discord.gg/pF8GSzbBEM" target="_blank">+ <!-- <img src="path-to-discord-icon.png" alt="Discord" /> -->+ Discord+ </a>+ </div>+ <div>+ <a href="mailto:[email protected]">Contact Us</a>+ </div>+ <p>© 2024 SmythOS an INK Content, Inc. company • 1321 Upland Dr. 1036 • Houston, TX 77339</p>+ <a href="https://smythos.com" target="_blank">www.smythos.com</a>+ </div>+ </div>+</body>+</html>diff --git a/packages/middleware/tsconfig.json b/packages/middleware/tsconfig.jsonnew file mode 100644index 00000000..493ae704--- /dev/null+++ b/packages/middleware/tsconfig.json@@ -0,0 +1,14 @@+{+ "compilerOptions": {+ "moduleResolution": "node",+ "target": "ES2020",+ "module": "ES2020",+ "esModuleInterop": true,+ "sourceMap": true,+ "outDir": "./static/js",+ "noImplicitAny": false,+ "resolveJsonModule": true,+ },+ "include": ["src/**/*", "node_modules/@types"],+ "exclude": ["node_modules"]+}diff --git a/packages/middleware/types/express-handlers.type.ts b/packages/middleware/types/express-handlers.type.tsnew file mode 100644index 00000000..27b87e83--- /dev/null+++ b/packages/middleware/types/express-handlers.type.ts@@ -0,0 +1,8 @@+import { RequestHandler } from 'express';++type WithError<T> = T & { code?: number; message?: string; stack?: string };++export type ExpressHandlerOptional<Req, Res> = RequestHandler<Record<string, string | undefined>, Partial<WithError<Res>>, Partial<Req>>;+export type ExpressHandler<Req, Res> = RequestHandler<Record<string, string>, WithError<Res>, Req>;++export type ExpressHandlerWithParams<Params, Req, Res> = RequestHandler<Params, WithError<Res>, Req, any>;diff --git a/packages/middleware/types/fields.type.ts b/packages/middleware/types/fields.type.tsnew file mode 100644index 00000000..4081386e--- /dev/null+++ b/packages/middleware/types/fields.type.ts@@ -0,0 +1,3 @@+import { Prisma } from '../src/utils/models';++export type PrismaTransaction = Prisma.TransactionClient;diff --git a/packages/middleware/types/index.ts b/packages/middleware/types/index.tsnew file mode 100644index 00000000..7322356d--- /dev/null+++ b/packages/middleware/types/index.ts@@ -0,0 +1,3 @@+export * from './express-handlers.type';+export * from './fields.type';+export * from './service.type';diff --git a/packages/middleware/types/service.type.ts b/packages/middleware/types/service.type.tsnew file mode 100644index 00000000..f439c615--- /dev/null+++ b/packages/middleware/types/service.type.ts@@ -0,0 +1,7 @@+import { PrismaTransaction } from './fields.type';++export type Transactional<T = object> = T & {+ ctx?: {+ tx?: PrismaTransaction;+ };+};diff --git a/packages/middleware/vitest.config.ts b/packages/middleware/vitest.config.tsnew file mode 100644index 00000000..c22b0d16--- /dev/null+++ b/packages/middleware/vitest.config.ts@@ -0,0 +1,14 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ globals: true,+ environment: 'node',+ },++ resolve: {+ alias: {+ // Removed @~internal alias as it was pointing to a non-existent path+ },+ },+});