Skip to content

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.

apply consistent prettier format by following existing packages

Forhad Hosain4ef62552aa0a
diff --git a/packages/runtime/package.json b/packages/runtime/package.json
index 1efb543c..ac26f2d9 100644
--- a/packages/runtime/package.json
+++ b/packages/runtime/package.json
@@ -13,8 +13,7 @@
"lint": "eslint --ext .ts src/",
"lint-fix": "eslint --ext .ts src/ --fix",
"ts-error-scan": "tsc --noEmit",
- "format": "prettier --write \"**/*.ts\"",
- "prettier:format": "prettier --write **/*.{js,jsx,ts,tsx,json,css,md}",
+ "prettier:format": "prettier --write \"**/*.ts\"",
"lint-staged": "lint-staged",
"bump": "pnpm version patch"
},
diff --git a/packages/runtime/src/core/component/Code.class.ts b/packages/runtime/src/core/component/Code.class.ts
index b9c5e625..4a7e938d 100644
--- a/packages/runtime/src/core/component/Code.class.ts
+++ b/packages/runtime/src/core/component/Code.class.ts
@@ -1,13 +1,13 @@
-import { Agent, Component, TemplateStringHelper } from "@smythos/sre";
-import axios from "axios";
-import Joi from "joi";
+import { Agent, Component, TemplateStringHelper } from '@smythos/sre';
+import axios from 'axios';
+import Joi from 'joi';
export class Code extends Component {
protected configSchema = Joi.object({
- code_vars: Joi.string().max(1000).allow("").label("Variables"),
- code_body: Joi.string().max(500000).allow("").label("Code"),
- _templateSettings: Joi.object().allow(null).label("Template Settings"),
- _templateVars: Joi.object().allow(null).label("Template Variables"),
+ code_vars: Joi.string().max(1000).allow('').label('Variables'),
+ code_body: Joi.string().max(500000).allow('').label('Code'),
+ _templateSettings: Joi.object().allow(null).label('Template Settings'),
+ _templateVars: Joi.object().allow(null).label('Template Variables'),
});
constructor() {
super();
@@ -20,23 +20,23 @@ export class Code extends Component {
try {
let Output: any = {};
let _error = undefined;
- const url = config.env.CODE_SANDBOX_URL + "/run-js";
+ const url = config.env.CODE_SANDBOX_URL + '/run-js';
let codeInputs = {};
for (let fieldName in input) {
const _type = typeof input[fieldName];
switch (_type) {
- case "string":
+ case 'string':
//escape string
//codeInputs[fieldName] = `\`${input[fieldName]}\``;
//encode string
- const b64encoded = Buffer.from(input[fieldName]).toString("base64");
+ const b64encoded = Buffer.from(input[fieldName]).toString('base64');
codeInputs[fieldName] = `___internal.b64decode('${b64encoded}')`;
break;
- case "number":
- case "boolean":
+ case 'number':
+ case 'boolean':
codeInputs[fieldName] = input[fieldName];
break;
default:
@@ -47,41 +47,29 @@ export class Code extends Component {
//FIXME : don't trust code_vars from user input ==> generate it
// let code_vars = parseTemplate(config.data.code_vars || '', codeInputs, { escapeString: false, processUnmatched: false });
- let code_vars = TemplateStringHelper.create(config.data.code_vars || "")
+ let code_vars = TemplateStringHelper.create(config.data.code_vars || '')
.parse(codeInputs)
- .clean(undefined, "undefined").result;
+ .clean(undefined, 'undefined').result;
//TODO: the current template parser doesn't support the processUnmatched or unmached options !!!!
// code_vars = parseTemplate(code_vars || '', codeInputs, { escapeString: false, unmached: 'undefined' });
let code_body = config.data.code_body;
if (config.data._templateVars) {
// code_body = parseTemplate(code_body, config.data._templateVars);
- code_body = TemplateStringHelper.create(code_body).parse(
- config.data._templateVars
- ).result;
+ code_body = TemplateStringHelper.create(code_body).parse(config.data._templateVars).result;
}
- const code = code_vars + "\n" + code_body;
+ const code = code_vars + '\n' + code_body;
logger.debug(` Running code \n${code}\n`);
- const result: any = await axios
- .post(url, { code })
- .catch((error) => ({ error }));
+ const result: any = await axios.post(url, { code }).catch(error => ({ error }));
if (result.error) {
- _error =
- result.error?.response?.data ||
- result.error?.message ||
- result.error.toString() ||
- "Unknown error";
- logger.error(
- ` Error running code \n${JSON.stringify(result.error, null, 2)}\n`
- );
+ _error = result.error?.response?.data || result.error?.message || result.error.toString() || 'Unknown error';
+ logger.error(` Error running code \n${JSON.stringify(result.error, null, 2)}\n`);
Output = undefined; //prevents running next component if the code execution failed
} else {
- logger.debug(
- ` Code result \n${JSON.stringify(result.data, null, 2)}\n`
- );
+ logger.debug(` Code result \n${JSON.stringify(result.data, null, 2)}\n`);
Output = result.data?.Output;
}
diff --git a/packages/runtime/src/core/component/componentRegistry.ts b/packages/runtime/src/core/component/componentRegistry.ts
index c33afcbd..552fcdac 100644
--- a/packages/runtime/src/core/component/componentRegistry.ts
+++ b/packages/runtime/src/core/component/componentRegistry.ts
@@ -1,22 +1,15 @@
-import {
- AccessCandidate,
- ComponentConnector,
- ConnectorService,
-} from "@smythos/sre";
+import { AccessCandidate, ComponentConnector, ConnectorService } from '@smythos/sre';
-import { Code } from "./Code.class";
+import { Code } from './Code.class';
-const COMPONENTS = [["Code", Code]] as const;
+const COMPONENTS = [['Code', Code]] as const;
/**
* Register all components
*/
export function registerComponents(): void {
- const componentConnector =
- ConnectorService.getComponentConnector() as ComponentConnector;
- const requester = componentConnector.requester(
- AccessCandidate.user("system")
- );
+ const componentConnector = ConnectorService.getComponentConnector() as ComponentConnector;
+ const requester = componentConnector.requester(AccessCandidate.user('system'));
COMPONENTS.forEach(([name, componentClass]) => {
requester.register(name, new componentClass());
diff --git a/packages/runtime/src/core/config.ts b/packages/runtime/src/core/config.ts
index bb4dd01d..63788ffd 100644
--- a/packages/runtime/src/core/config.ts
+++ b/packages/runtime/src/core/config.ts
@@ -1,6 +1,6 @@
-import dotenv from "dotenv";
-import path from "path";
-import { fileURLToPath } from "url";
+import dotenv from 'dotenv';
+import path from 'path';
+import { fileURLToPath } from 'url';
dotenv.config();
@@ -9,17 +9,17 @@ const __dirname = path.dirname(__filename);
const config = {
env: {
- PORT: parseInt(process.env.PORT || "5053"),
+ PORT: parseInt(process.env.PORT || '5053'),
// Required environment variables
LOGTO_M2M_APP_SECRET: process.env.LOGTO_M2M_APP_SECRET,
LOGTO_SERVER: process.env.LOGTO_SERVER,
LOGTO_API_RESOURCE: process.env.LOGTO_API_RESOURCE,
MIDDLEWARE_API_BASE_URL: process.env.MIDDLEWARE_API_BASE_URL,
- NODE_ENV: process.env?.NODE_ENV || "development",
+ NODE_ENV: process.env?.NODE_ENV || 'development',
ADMIN_PORT: process.env.ADMIN_PORT || 5054,
- BASE_URL: process.env.BASE_URL || "http://localhost:5053",
+ BASE_URL: process.env.BASE_URL || 'http://localhost:5053',
LOGTO_M2M_APP_ID: process.env.LOGTO_M2M_APP_ID,
@@ -30,12 +30,12 @@ const config = {
REQ_LIMIT_PER_MINUTE: process.env.REQ_LIMIT_PER_MINUTE || 300,
MAX_CONCURRENT_REQUESTS: process.env.MAX_CONCURRENT_REQUESTS || 10,
- UI_SERVER: process.env.UI_SERVER || "http://localhost:4000",
+ UI_SERVER: process.env.UI_SERVER || 'http://localhost:4000',
SESSION_SECRET: process.env.SESSION_SECRET,
- DATA_PATH: process.env.DATA_PATH || path.resolve(__dirname, "../../data"),
+ DATA_PATH: process.env.DATA_PATH || path.resolve(__dirname, '../../data'),
- SMYTHOS_SERVER_TYPE: process.env.SMYTHOS_SERVER_TYPE || "combined",
+ SMYTHOS_SERVER_TYPE: process.env.SMYTHOS_SERVER_TYPE || 'combined',
},
};
diff --git a/packages/runtime/src/core/config/index.ts b/packages/runtime/src/core/config/index.ts
index b0ddd04b..ec60ea1b 100644
--- a/packages/runtime/src/core/config/index.ts
+++ b/packages/runtime/src/core/config/index.ts
@@ -1,6 +1,6 @@
/**
* Core Configuration Exports
- *
+ *
* This file provides centralized exports for all configuration modules
* in the SmythOS runtime environment.
*/
diff --git a/packages/runtime/src/core/config/models.config.ts b/packages/runtime/src/core/config/models.config.ts
index 7b39ad3c..0f7e1c05 100644
--- a/packages/runtime/src/core/config/models.config.ts
+++ b/packages/runtime/src/core/config/models.config.ts
@@ -5,7 +5,7 @@
* from a JSON file for better maintainability.
*/
-import modelsData from "@data/models.json";
+import modelsData from '@data/models.json';
// Base interface with all possible fields for non-Echo models
interface BaseModelConfig {
@@ -30,7 +30,7 @@ interface BaseModelConfig {
// Echo model configuration (only requires provider)
interface EchoModelConfig {
- provider: "Echo";
+ provider: 'Echo';
}
// Conditional type: if provider is "Echo", use EchoModelConfig, otherwise use BaseModelConfig
diff --git a/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts b/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts
index eea9908a..3fc900b4 100644
--- a/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts
+++ b/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts
@@ -1,4 +1,4 @@
-import axios, { AxiosInstance } from "axios";
+import axios, { AxiosInstance } from 'axios';
import {
AccessRequest,
@@ -11,14 +11,14 @@ import {
OAuthConfig,
TAccessLevel,
TAccessRole,
-} from "@smythos/sre";
+} from '@smythos/sre';
-import { getM2MToken } from "@core/helpers/logto.helper";
-import { SmythConfigs } from "@core/types/general.types";
+import { getM2MToken } from '@core/helpers/logto.helper';
+import { SmythConfigs } from '@core/types/general.types';
-const console = Logger("SmythOSSAccount");
+const console = Logger('SmythOSSAccount');
export class SmythOSSAccount extends AccountConnector {
- public name: string = "SmythOSSAccount";
+ public name: string = 'SmythOSSAccount';
private oAuthAppId: string;
private oAuthAppSecret: string;
private oAuthBaseUrl: string;
@@ -33,17 +33,14 @@ export class SmythOSSAccount extends AccountConnector {
this.oAuthAppId = _settings.oAuthAppID;
this.oAuthAppSecret = _settings.oAuthAppSecret;
this.oAuthBaseUrl = _settings.oAuthBaseUrl;
- this.oAuthResource = _settings.oAuthResource || "";
- this.oAuthScope = _settings.oAuthScope || "";
+ this.oAuthResource = _settings.oAuthResource || '';
+ this.oAuthScope = _settings.oAuthScope || '';
this.smythAPI = axios.create({
baseURL: `${_settings.smythAPIBaseUrl}`,
});
}
- public async isTeamMember(
- teamId: string,
- candidate: IAccessCandidate
- ): Promise<boolean> {
+ public async isTeamMember(teamId: string, candidate: IAccessCandidate): Promise<boolean> {
try {
const candidateTeamId = await this.getCandidateTeam(candidate);
if (teamId === candidateTeamId) {
@@ -55,9 +52,7 @@ export class SmythOSSAccount extends AccountConnector {
}
}
- public async getCandidateTeam(
- candidate: IAccessCandidate
- ): Promise<string | undefined> {
+ public async getCandidateTeam(candidate: IAccessCandidate): Promise<string | undefined> {
if (candidate.role === TAccessRole.Team) {
return candidate.id;
}
@@ -76,10 +71,7 @@ export class SmythOSSAccount extends AccountConnector {
return null;
}
- public async getAllTeamSettings(
- acRequest: AccessRequest,
- teamId: string
- ): Promise<KeyValueObject | null> {
+ public async getAllTeamSettings(acRequest: AccessRequest, teamId: string): Promise<KeyValueObject | null> {
try {
const response = await this.smythAPI.get(`/v1/teams/${teamId}/settings`, {
headers: await this.getSmythRequestHeaders(),
@@ -98,15 +90,9 @@ export class SmythOSSAccount extends AccountConnector {
}
}
- public async getAllUserSettings(
- acRequest: AccessRequest,
- accountId: string
- ): Promise<KeyValueObject | null> {
+ public async getAllUserSettings(acRequest: AccessRequest, accountId: string): Promise<KeyValueObject | null> {
try {
- const response = await this.smythAPI.get(
- `/v1/user/${accountId}/settings`,
- { headers: await this.getSmythRequestHeaders() }
- );
+ const response = await this.smythAPI.get(`/v1/user/${accountId}/settings`, { headers: await this.getSmythRequestHeaders() });
if (response?.data?.settings?.length > 0) {
const settingsObject: KeyValueObject = {};
@@ -121,34 +107,20 @@ export class SmythOSSAccount extends AccountConnector {
}
}
- public async getTeamSetting(
- acRequest: AccessRequest,
- teamId: string,
- settingKey: string
- ): Promise<string> {
+ public async getTeamSetting(acRequest: AccessRequest, teamId: string, settingKey: string): Promise<string> {
try {
- const response = await this.smythAPI.get(
- `/v1/teams/${teamId}/settings/${settingKey}`,
- { headers: await this.getSmythRequestHeaders() }
- );
+ const response = await this.smythAPI.get(`/v1/teams/${teamId}/settings/${settingKey}`, { headers: await this.getSmythRequestHeaders() });
return response?.data?.setting?.settingValue || null;
} catch (error) {
return null;
}
}
- public async getUserSetting(
- acRequest: AccessRequest,
- accountId: string,
- settingKey: string
- ): Promise<string> {
+ public async getUserSetting(acRequest: AccessRequest, accountId: string, settingKey: string): Promise<string> {
try {
- const response = await this.smythAPI.get(
- `/v1/user/${accountId}/settings/${settingKey}`,
- {
- headers: await this.getSmythRequestHeaders(),
- }
- );
+ const response = await this.smythAPI.get(`/v1/user/${accountId}/settings/${settingKey}`, {
+ headers: await this.getSmythRequestHeaders(),
+ });
return response?.data?.setting?.settingValue || null;
} catch (error) {
return null;
@@ -156,8 +128,7 @@ export class SmythOSSAccount extends AccountConnector {
}
public async getResourceACL(resourceId: string, candidate: IAccessCandidate) {
- const accountConnector =
- ConnectorService.getAccountConnector("SmythAccount");
+ const accountConnector = ConnectorService.getAccountConnector('SmythAccount');
const teamId = await accountConnector.getCandidateTeam(candidate);
const acl = new ACL();
@@ -182,30 +153,20 @@ export class SmythOSSAccount extends AccountConnector {
};
}
- public async getAgentSetting(
- acRequest: AccessRequest,
- agentId: string,
- settingKey: string
- ): Promise<string> {
+ public async getAgentSetting(acRequest: AccessRequest, agentId: string, settingKey: string): Promise<string> {
try {
// TODO: use following endpoint when Ahmed make it available
// const response = await this.smythAPI.get(`/v1/ai-agent/${agentId}/settings/${settingKey}`, {
// headers: await this.getSmythRequestHeaders(),
// });
- const response = await this.smythAPI.get(
- `/v1/ai-agent/${agentId}/settings/`,
- {
- headers: await this.getSmythRequestHeaders(),
- }
- );
- const setting =
- response?.data?.settings?.find(
- (setting: KeyValueObject) => setting?.key === settingKey
- ) || null;
- return setting?.value || "";
+ const response = await this.smythAPI.get(`/v1/ai-agent/${agentId}/settings/`, {
+ headers: await this.getSmythRequestHeaders(),
+ });
+ const setting = response?.data?.settings?.find((setting: KeyValueObject) => setting?.key === settingKey) || null;
+ return setting?.value || '';
} catch (error) {
- return "";
+ return '';
}
}
}
diff --git a/packages/runtime/src/core/connectors/SmythOSSAgentDataConnector.class.ts b/packages/runtime/src/core/connectors/SmythOSSAgentDataConnector.class.ts
index 13e20980..5f784462 100644
--- a/packages/runtime/src/core/connectors/SmythOSSAgentDataConnector.class.ts
+++ b/packages/runtime/src/core/connectors/SmythOSSAgentDataConnector.class.ts
@@ -1,12 +1,12 @@
-import axios, { AxiosInstance } from "axios";
+import axios, { AxiosInstance } from 'axios';
-import { AgentDataConnector, OAuthConfig } from "@smythos/sre";
+import { AgentDataConnector, OAuthConfig } from '@smythos/sre';
-import { getM2MToken } from "@core/helpers/logto.helper";
-import { SmythConfigs } from "@core/types/general.types";
+import { getM2MToken } from '@core/helpers/logto.helper';
+import { SmythConfigs } from '@core/types/general.types';
export class SmythOSSAgentDataConnector extends AgentDataConnector {
- public name: string = "SmythOSSAgentData";
+ public name: string = 'SmythOSSAgentData';
private oAuthAppId: string;
private oAuthAppSecret: string;
private oAuthBaseUrl: string;
@@ -16,17 +16,14 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
private agentStageDomain: string;
private agentProdDomain: string;
- constructor(
- private config: SmythConfigs &
- OAuthConfig & { agentStageDomain: string; agentProdDomain: string }
- ) {
+ constructor(private config: SmythConfigs & OAuthConfig & { agentStageDomain: string; agentProdDomain: string }) {
super();
//if (!SmythRuntime.Instance) throw new Error('SRE not initialized');
this.oAuthAppId = config.oAuthAppID;
this.oAuthAppSecret = config.oAuthAppSecret;
this.oAuthBaseUrl = config.oAuthBaseUrl;
- this.oAuthResource = config.oAuthResource || "";
- this.oAuthScope = config.oAuthScope || "";
+ this.oAuthResource = config.oAuthResource || '';
+ this.oAuthScope = config.oAuthScope || '';
this.smythAPI = axios.create({
baseURL: `${config.smythAPIBaseUrl}`,
});
@@ -47,49 +44,34 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
//FIXME : once we have the agent name in deployment api response, we can skip this call
// const response = await mwSysAPI.get(`/ai-agent/${agentID}?include=team.subscription`, includeAuth(token));
- const response = await this.smythAPI.get(
- `/v1/ai-agent/${agentId}?include=team.subscription`,
- {
- headers: await this.getSmythRequestHeaders(),
- }
- );
+ const response = await this.smythAPI.get(`/v1/ai-agent/${agentId}?include=team.subscription`, {
+ headers: await this.getSmythRequestHeaders(),
+ });
agentObj = response.data.agent;
const authData = agentObj.data.auth; //use most up to date auth data
// const tasksResponse = await mwSysAPI.get(`/quota/team/${agentObj.teamId}/tasks/subscription`, includeAuth(token));
- const tasksResponse = await this.smythAPI.get(
- `/v1/quota/team/${agentObj.teamId}/tasks/subscription`,
- {
- headers: await this.getSmythRequestHeaders(),
- }
- );
+ const tasksResponse = await this.smythAPI.get(`/v1/quota/team/${agentObj.teamId}/tasks/subscription`, {
+ headers: await this.getSmythRequestHeaders(),
+ });
agentObj.taskData = tasksResponse.data;
- agentObj.data.debugSessionEnabled =
- agentObj?.data?.debugSessionEnabled && agentObj?.isLocked; //disable debug session if agent is not locked (locked agent means that it's open in the Agent builder)
+ agentObj.data.debugSessionEnabled = agentObj?.data?.debugSessionEnabled && agentObj?.isLocked; //disable debug session if agent is not locked (locked agent means that it's open in the Agent builder)
if (version) {
// const deploymentsList = await mwSysAPI.get(`/ai-agent/${agentID}/deployments`, includeAuth(token));
- const deploymentsList = await this.smythAPI.get(
- `/v1/ai-agent/${agentId}/deployments`,
- {
- headers: await this.getSmythRequestHeaders(),
- }
- );
+ const deploymentsList = await this.smythAPI.get(`/v1/ai-agent/${agentId}/deployments`, {
+ headers: await this.getSmythRequestHeaders(),
+ });
const deployment =
- version == "latest"
+ version == 'latest'
? deploymentsList?.data?.deployments[0]
- : deploymentsList?.data?.deployments?.find(
- (deployment) => deployment.version === version
- );
+ : deploymentsList?.data?.deployments?.find(deployment => deployment.version === version);
if (deployment) {
// const deployResponse = await mwSysAPI.get(`/ai-agent/deployments/${deployment.id}`, includeAuth(token));
- const deployResponse = await this.smythAPI.get(
- `/v1/ai-agent/deployments/${deployment.id}`,
- {
- headers: await this.getSmythRequestHeaders(),
- }
- );
+ const deployResponse = await this.smythAPI.get(`/v1/ai-agent/deployments/${deployment.id}`, {
+ headers: await this.getSmythRequestHeaders(),
+ });
agentObj.data = deployResponse?.data?.deployment?.aiAgentData;
agentObj.data.debugSessionEnabled = false; //never enable debug session when using a deployed version
agentObj.data.agentVersion = deployment.version;
@@ -104,23 +86,15 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
//TODO: Also include team and subscription info
//agentObj.data.auth = authData;
- if (
- !agentObj?.data?.auth?.method ||
- agentObj?.data?.auth?.method == "none"
- )
- agentObj.data.auth = authData;
+ if (!agentObj?.data?.auth?.method || agentObj?.data?.auth?.method == 'none') agentObj.data.auth = authData;
agentObj.data = this.migrateAgentData(agentObj.data);
return agentObj;
} catch (error: any) {
console.error(error.response?.data, error.message);
- console.log(
- `Error getting agent data for agentId=${agentId}: ${error?.message}`
- );
- throw new Error(
- `Error getting agent data for agentId=${agentId}: ${error?.message}`
- );
+ console.log(`Error getting agent data for agentId=${agentId}: ${error?.message}`);
+ throw new Error(`Error getting agent data for agentId=${agentId}: ${error?.message}`);
}
}
@@ -131,12 +105,9 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
const isProdWildcardDomain = domain.includes(this.agentProdDomain);
if (isStageWildcardDomain || isProdWildcardDomain) {
//console.log('Internal agent domain detected', domain);
- agentId = domain.split(".")[0];
+ agentId = domain.split('.')[0];
//sanity check
- if (
- `${agentId}.${this.agentStageDomain}` !== domain &&
- `${agentId}.${this.agentProdDomain}` !== domain
- ) {
+ if (`${agentId}.${this.agentStageDomain}` !== domain && `${agentId}.${this.agentProdDomain}` !== domain) {
throw new Error(`Invalid agent domain: ${domain}`);
}
@@ -149,24 +120,20 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
.get(`/v1/domains?verified=true`, {
headers: await this.getSmythRequestHeaders(),
})
- .catch((error) => ({ error }));
+ .catch(error => ({ error }));
if (result.error) {
- throw new Error("Error getting domain info");
+ throw new Error('Error getting domain info');
}
//we have an agentId from the wildcard domain, if this domain is already associated with
if (agentId) {
- const hasDomain = result.data.domains.find(
- (domainEntry: any) => domainEntry?.aiAgent?.id === agentId
- );
+ const hasDomain = result.data.domains.find((domainEntry: any) => domainEntry?.aiAgent?.id === agentId);
if (hasDomain) {
- throw new Error("Wrong domain");
+ throw new Error('Wrong domain');
}
} else {
- agentId = result.data.domains.find(
- (domainEntry: any) => domainEntry.name === domain
- )?.aiAgent?.id;
+ agentId = result.data.domains.find((domainEntry: any) => domainEntry.name === domain)?.aiAgent?.id;
}
//if a custom domain is found, use it, otherwise use the agentId from the wildcard domain
@@ -174,95 +141,59 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
return agentId;
}
- public async getAgentSettings(
- agentId: string,
- version?: string
- ): Promise<any> {
+ public async getAgentSettings(agentId: string, version?: string): Promise<any> {
try {
// If no matching deployment found or no deployments at all, return the current live settings
- const response = await this.smythAPI.get(
- `/v1/ai-agent/${agentId}/settings`,
- {
- headers: await this.getSmythRequestHeaders(),
- }
- );
- const formattedSettings = response.data.settings.reduce(
- (acc, setting) => ({ ...acc, [setting.key]: setting.value }),
- {}
- );
+ const response = await this.smythAPI.get(`/v1/ai-agent/${agentId}/settings`, {
+ headers: await this.getSmythRequestHeaders(),
+ });
+ const formattedSettings = response.data.settings.reduce((acc, setting) => ({ ...acc, [setting.key]: setting.value }), {});
return formattedSettings;
} catch (error) {
- console.error(
- `Error getting agent settings for agentId=${agentId}: ${error?.message}`
- );
- throw new Error(
- `Error getting agent settings for agentId=${agentId}: ${error?.message}`
- );
+ console.error(`Error getting agent settings for agentId=${agentId}: ${error?.message}`);
+ throw new Error(`Error getting agent settings for agentId=${agentId}: ${error?.message}`);
}
}
- public async getAgentEmbodiments(
- agentId: string,
- version?: string
- ): Promise<any> {
+ public async getAgentEmbodiments(agentId: string, version?: string): Promise<any> {
try {
// If no matching deployment found or no deployments at all, return the current live settings
- const response = await this.smythAPI.get(
- `/v1/embodiments?aiAgentId=${agentId}`,
- {
- headers: await this.getSmythRequestHeaders(),
- }
- );
+ const response = await this.smythAPI.get(`/v1/embodiments?aiAgentId=${agentId}`, {
+ headers: await this.getSmythRequestHeaders(),
+ });
return response?.data?.embodiments || [];
} catch (error) {
- console.error(
- `Error getting agent embodiments for agentId=${agentId}: ${error?.message}`
- );
- throw new Error(
- `Error getting agent embodiments for agentId=${agentId}: ${error?.message}`
- );
+ console.error(`Error getting agent embodiments for agentId=${agentId}: ${error?.message}`);
+ throw new Error(`Error getting agent embodiments for agentId=${agentId}: ${error?.message}`);
}
}
- public async listTeamAgents(
- teamId: string,
- deployedOnly?: boolean,
- includeData?: boolean
- ): Promise<any[]> {
+ public async listTeamAgents(teamId: string, deployedOnly?: boolean, includeData?: boolean): Promise<any[]> {
try {
const headers = await this.getSmythRequestHeaders();
// If no matching deployment found or no deployments at all, return the current live settings
const response = await this.smythAPI.get(
- `/v1/ai-agent/teams/${teamId}/?deployedOnly=${
- deployedOnly ? "true" : "false"
- }&includeData=${includeData ? "true" : "false"}`,
+ `/v1/ai-agent/teams/${teamId}/?deployedOnly=${deployedOnly ? 'true' : 'false'}&includeData=${includeData ? 'true' : 'false'}`,
{
headers,
- }
+ },
);
const agentsList = response?.data?.agents;
return agentsList;
} catch (error) {
- console.error(
- `Error listing team agents for teamId=${teamId}: ${error?.message}`
- );
- throw new Error(
- `Error listing team agents for teamId=${teamId}: ${error?.message}`
- );
+ console.error(`Error listing team agents for teamId=${teamId}: ${error?.message}`);
+ throw new Error(`Error listing team agents for teamId=${teamId}: ${error?.message}`);
}
}
public async isDeployed(agentId: string): Promise<boolean> {
try {
- const deploymentsList = await this.smythAPI.get(
- `/v1/ai-agent/${agentId}/deployments`,
- {
- headers: await this.getSmythRequestHeaders(),
- }
- );
+ const deploymentsList = await this.smythAPI.get(`/v1/ai-agent/${agentId}/deployments`, {
+ headers: await this.getSmythRequestHeaders(),
+ });
return deploymentsList?.data?.deployments?.length > 0;
} catch (error) {
console.error(error);
@@ -284,9 +215,7 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
private migrateAgentData(data) {
if (!data.version) {
- console.log(
- `Agent [${data.name}] has an old schema. Migrating to latest version...`
- );
+ console.log(`Agent [${data.name}] has an old schema. Migrating to latest version...`);
// version 0 ===> migrate from receptors/connectors to inputs/outputs
const newData = JSON.parse(JSON.stringify(data));
for (let component of newData.components) {
@@ -302,7 +231,7 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
return newData;
}
- if (data.version === "1.0.0") {
+ if (data.version === '1.0.0') {
//migrate .description to .behavior
if (data.description && !data.behavior) {
data.behavior = data.description;
diff --git a/packages/runtime/src/core/connectors/SmythOSSVault.class.ts b/packages/runtime/src/core/connectors/SmythOSSVault.class.ts
index b3eca2b2..ca0aee8a 100644
--- a/packages/runtime/src/core/connectors/SmythOSSVault.class.ts
+++ b/packages/runtime/src/core/connectors/SmythOSSVault.class.ts
@@ -1,4 +1,4 @@
-import axios, { AxiosInstance } from "axios";
+import axios, { AxiosInstance } from 'axios';
import {
AccessRequest,
@@ -11,17 +11,17 @@ import {
TAccessLevel,
TAccessRole,
VaultConnector,
-} from "@smythos/sre";
+} from '@smythos/sre';
-import { getM2MToken } from "@core/helpers/logto.helper";
+import { getM2MToken } from '@core/helpers/logto.helper';
export type SmythVaultConfig = {
vaultAPIBaseUrl: string;
};
-const console = Logger("SmythOSSVault");
+const console = Logger('SmythOSSVault');
export class SmythOSSVault extends VaultConnector {
- public name: string = "SmythOSSVault";
+ public name: string = 'SmythOSSVault';
private oAuthAppId: string;
private oAuthAppSecret: string;
private oAuthBaseUrl: string;
@@ -36,8 +36,8 @@ export class SmythOSSVault extends VaultConnector {
this.oAuthAppId = _settings.oAuthAppID;
this.oAuthAppSecret = _settings.oAuthAppSecret;
this.oAuthBaseUrl = _settings.oAuthBaseUrl;
- this.oAuthResource = _settings.oAuthResource || "";
- this.oAuthScope = _settings.oAuthScope || "";
+ this.oAuthResource = _settings.oAuthResource || '';
+ this.oAuthScope = _settings.oAuthScope || '';
this.vaultAPI = axios.create({
baseURL: `${_settings.vaultAPIBaseUrl}/v1/api`,
});
@@ -49,24 +49,16 @@ export class SmythOSSVault extends VaultConnector {
const teamId = await accountConnector.getCandidateTeam(acRequest.candidate);
const vaultAPIHeaders = await this.getVaultRequestHeaders();
- let key = "";
+ let key = '';
try {
- const vaultResponse = await this.vaultAPI.get(
- `/vault/${teamId}/secrets/${keyId}`,
- { headers: vaultAPIHeaders }
- );
+ const vaultResponse = await this.vaultAPI.get(`/vault/${teamId}/secrets/${keyId}`, { headers: vaultAPIHeaders });
key = vaultResponse?.data?.secret?.value || null;
} catch (error) {
- console.warn(
- `Warn: Failed to get key "${keyId}" from SmythVault, trying to get it from the legacy vault`
- );
+ console.warn(`Warn: Failed to get key "${keyId}" from SmythVault, trying to get it from the legacy vault`);
}
if (!key) {
- const vaultResponse = await this.vaultAPI.get(
- `/vault/${teamId}/secrets/name/${keyId}`,
- { headers: vaultAPIHeaders }
- );
+ const vaultResponse = await this.vaultAPI.get(`/vault/${teamId}/secrets/name/${keyId}`, { headers: vaultAPIHeaders });
key = vaultResponse?.data?.secret?.value || null;
}
@@ -74,12 +66,8 @@ export class SmythOSSVault extends VaultConnector {
if (!key) {
// * Note: Adjustment for legacy global vault keys, we can remove it after migrating all keys in Hashicorp Vault with proper key ID such as 'googleai' -> 'GoogleAI'
const legacyGlobalVaultKey = keyId.toLowerCase();
- const globalVaultKey =
- legacyGlobalVaultKey === "anthropic" ? "claude" : legacyGlobalVaultKey; // Ensure backward compatibility: In SaaS the key was stored under 'claude';
- const vaultResponse = await this.vaultAPI.get(
- `/vault/${teamId}/secrets/${globalVaultKey}`,
- { headers: vaultAPIHeaders }
- );
+ const globalVaultKey = legacyGlobalVaultKey === 'anthropic' ? 'claude' : legacyGlobalVaultKey; // Ensure backward compatibility: In SaaS the key was stored under 'claude';
+ const vaultResponse = await this.vaultAPI.get(`/vault/${teamId}/secrets/${globalVaultKey}`, { headers: vaultAPIHeaders });
return vaultResponse?.data?.secret?.value;
}
@@ -92,10 +80,7 @@ export class SmythOSSVault extends VaultConnector {
const accountConnector = ConnectorService.getAccountConnector();
const teamId = await accountConnector.getCandidateTeam(acRequest.candidate);
const vaultAPIHeaders = await this.getVaultRequestHeaders();
- const vaultResponse = await this.vaultAPI.get(
- `/vault/${teamId}/secrets/${keyId}`,
- { headers: vaultAPIHeaders }
- );
+ const vaultResponse = await this.vaultAPI.get(`/vault/${teamId}/secrets/${keyId}`, { headers: vaultAPIHeaders });
return vaultResponse?.data?.secret ? true : false;
}
@@ -114,7 +99,7 @@ export class SmythOSSVault extends VaultConnector {
secret.metadata.scope = JSON.parse(secret.metadata.scope);
} catch (error) {
secret.metadata.scope = [];
- console.error("Error:", error);
+ console.error('Error:', error);
}
}
});
diff --git a/packages/runtime/src/core/connectors/connectorRegistry.ts b/packages/runtime/src/core/connectors/connectorRegistry.ts
index ab330359..f871ed0f 100644
--- a/packages/runtime/src/core/connectors/connectorRegistry.ts
+++ b/packages/runtime/src/core/connectors/connectorRegistry.ts
@@ -1,22 +1,14 @@
-import {
- ConnectorService,
- JSONModelsProvider,
- TConnectorService,
-} from "@smythos/sre";
+import { ConnectorService, JSONModelsProvider, TConnectorService } from '@smythos/sre';
-import { SmythOSSAccount } from "./SmythOSSAccount.class";
-import { SmythOSSAgentDataConnector } from "./SmythOSSAgentDataConnector.class";
-import { SmythOSSVault } from "./SmythOSSVault.class";
+import { SmythOSSAccount } from './SmythOSSAccount.class';
+import { SmythOSSAgentDataConnector } from './SmythOSSAgentDataConnector.class';
+import { SmythOSSVault } from './SmythOSSVault.class';
const CONNECTORS = [
- [
- TConnectorService.AgentData,
- "SmythOSSAgentData",
- SmythOSSAgentDataConnector,
- ],
- [TConnectorService.Account, "SmythOSSAccount", SmythOSSAccount],
- [TConnectorService.Vault, "SmythOSSVault", SmythOSSVault],
- [TConnectorService.ModelsProvider, "SmythModelsProvider", JSONModelsProvider],
+ [TConnectorService.AgentData, 'SmythOSSAgentData', SmythOSSAgentDataConnector],
+ [TConnectorService.Account, 'SmythOSSAccount', SmythOSSAccount],
+ [TConnectorService.Vault, 'SmythOSSVault', SmythOSSVault],
+ [TConnectorService.ModelsProvider, 'SmythModelsProvider', JSONModelsProvider],
] as const;
/**
diff --git a/packages/runtime/src/core/constants.ts b/packages/runtime/src/core/constants.ts
index 56b6c0a8..e1c0337e 100644
--- a/packages/runtime/src/core/constants.ts
+++ b/packages/runtime/src/core/constants.ts
@@ -1,17 +1,11 @@
-export const DEFAULT_AGENT_MODEL_SETTINGS_KEY = "chatGptModel"; // the key in the agent settings object that contains the model name
-export const DEFAULT_MODEL = "gpt-5-mini"; // the default model to use if no model is specified in the agent settings
+export const DEFAULT_AGENT_MODEL_SETTINGS_KEY = 'chatGptModel'; // the key in the agent settings object that contains the model name
+export const DEFAULT_MODEL = 'gpt-5-mini'; // the default model to use if no model is specified in the agent settings
-export const PROD_VERSION_VALUES = ["prod", "production", "stable"];
-export const TEST_VERSION_VALUES = [
- "dev",
- "develop",
- "development",
- "test",
- "staging",
-];
+export const PROD_VERSION_VALUES = ['prod', 'production', 'stable'];
+export const TEST_VERSION_VALUES = ['dev', 'develop', 'development', 'test', 'staging'];
export const MAX_FILE_SIZE = 5 * 1024 * 1024; // 5 MB
export const MAX_FILE_COUNT = 5;
-export const AGENT_AUTH_SETTINGS_KEY = "agentAuth";
-export const MOCK_DATA_SETTINGS_KEY = "agent-mock-data";
+export const AGENT_AUTH_SETTINGS_KEY = 'agentAuth';
+export const MOCK_DATA_SETTINGS_KEY = 'agent-mock-data';
diff --git a/packages/runtime/src/core/default-file-parsing-agent.ts b/packages/runtime/src/core/default-file-parsing-agent.ts
index b3ec2f07..b0576aae 100644
--- a/packages/runtime/src/core/default-file-parsing-agent.ts
+++ b/packages/runtime/src/core/default-file-parsing-agent.ts
@@ -1,119 +1,117 @@
-import { DEFAULT_MODEL } from "@core/constants";
+import { DEFAULT_MODEL } from '@core/constants';
export const defaultFileParsingAgent = {
components: [
{
- id: "CM6JHAW8TNQB",
- name: "APIEndpoint",
+ id: 'CM6JHAW8TNQB',
+ 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: 'headers', color: '#3C89F9', index: 0, default: true },
+ { name: 'body', color: '#3C89F9', index: 1, default: true },
+ { name: 'query', color: '#3C89F9', index: 2, default: true },
{
- name: "message",
- color: "#3C89F9",
- expression: "body.message",
+ name: 'message',
+ color: '#3C89F9',
+ expression: 'body.message',
index: 3,
default: false,
},
{
- name: "attachments",
- color: "#3C89F9",
- expression: "body.attachments",
+ name: 'attachments',
+ color: '#3C89F9',
+ expression: 'body.attachments',
index: 4,
default: false,
},
],
inputs: [
{
- name: "message",
- type: "Any",
- friendlyInputType: "Text",
- coreInputType: "Any",
- color: "#F35063",
+ name: 'message',
+ type: 'Any',
+ friendlyInputType: 'Text',
+ coreInputType: 'Any',
+ color: '#F35063',
optional: false,
description: "User's query.",
index: 0,
default: false,
},
{
- name: "attachments",
- type: "Binary",
- friendlyInputType: "Text",
- coreInputType: "Binary",
- color: "#F35063",
+ name: 'attachments',
+ type: 'Binary',
+ friendlyInputType: 'Text',
+ coreInputType: 'Binary',
+ color: '#F35063',
optional: false,
- description:
- "Files, images, and attachments to parse and answer questions about.",
+ description: 'Files, images, and attachments to parse and answer questions about.',
index: 1,
default: false,
},
],
data: {
- method: "POST",
- endpoint: "process_attachment_fallback",
- description:
- "Use this endpoint to process user queries with attachments, if there is no other endpoint to process the attachments.",
+ method: 'POST',
+ endpoint: 'process_attachment_fallback',
+ description: 'Use this endpoint to process user queries with attachments, if there is no other endpoint to process the attachments.',
ai_exposed: true,
- summary: "",
+ summary: '',
advancedModeEnabled: false,
},
- top: "72.6576px",
- left: "539.408px",
- width: "",
- height: "",
- displayName: "APIEndpoint",
- title: "Agent Skill",
- aiTitle: "",
- description: "An API Endpoint with input parameters for your AI agent.",
+ top: '72.6576px',
+ left: '539.408px',
+ width: '',
+ height: '',
+ displayName: 'APIEndpoint',
+ title: 'Agent Skill',
+ aiTitle: '',
+ description: 'An API Endpoint with input parameters for your AI agent.',
},
{
- id: "CM6JHDY7QJR",
- name: "APIOutput",
- outputs: [{ name: "Output", color: "#3C89F9", index: 0, default: true }],
+ id: 'CM6JHDY7QJR',
+ name: 'APIOutput',
+ outputs: [{ name: 'Output', color: '#3C89F9', index: 0, default: true }],
inputs: [
{
- name: "result",
- type: "Any",
- friendlyInputType: "",
- coreInputType: "Any",
- color: "#F35063",
+ name: 'result',
+ type: 'Any',
+ friendlyInputType: '',
+ coreInputType: 'Any',
+ color: '#F35063',
optional: false,
index: 0,
default: false,
},
],
- data: { format: "minimal" },
- top: "131.801px",
- left: "1269.49px",
- width: "",
- height: "",
- displayName: "APIOutput",
- title: "APIOutput",
- aiTitle: "",
- description: "",
+ data: { format: 'minimal' },
+ top: '131.801px',
+ left: '1269.49px',
+ width: '',
+ height: '',
+ displayName: 'APIOutput',
+ title: 'APIOutput',
+ aiTitle: '',
+ description: '',
},
{
- id: "CM6QMI3IGUCK",
- name: "GenAILLM",
- outputs: [{ name: "Reply", color: "#3C89F9", index: 0, default: true }],
+ id: 'CM6QMI3IGUCK',
+ name: 'GenAILLM',
+ outputs: [{ name: 'Reply', color: '#3C89F9', index: 0, default: true }],
inputs: [
{
- name: "Input",
- type: "Any",
- friendlyInputType: "",
- coreInputType: "",
- color: "#F35063",
+ name: 'Input',
+ type: 'Any',
+ friendlyInputType: '',
+ coreInputType: '',
+ color: '#F35063',
optional: false,
index: 0,
default: false,
},
{
- name: "Attachment",
- type: "Binary",
- friendlyInputType: "",
- coreInputType: "",
- color: "#F35063",
+ name: 'Attachment',
+ type: 'Binary',
+ friendlyInputType: '',
+ coreInputType: '',
+ color: '#F35063',
optional: true,
index: 1,
default: false,
@@ -121,46 +119,44 @@ export const defaultFileParsingAgent = {
],
data: {
model: DEFAULT_MODEL,
- prompt:
- "Answer question the user's questions: {{Input}}\nUse the attachments for context if needed.",
- temperature: "1",
- maxTokens: "16384",
- topP: "1",
- topK: "0",
- frequencyPenalty: "0",
- presencePenalty: "0",
+ prompt: "Answer question the user's questions: {{Input}}\nUse the attachments for context if needed.",
+ temperature: '1',
+ maxTokens: '16384',
+ topP: '1',
+ topK: '0',
+ frequencyPenalty: '0',
+ presencePenalty: '0',
passthrough: false,
- stopSequences: "",
- maxThinkingTokens: "816",
+ stopSequences: '',
+ maxThinkingTokens: '816',
},
- top: "34.9306px",
- left: "902.845px",
- width: "",
- height: "",
- displayName: "GenAI LLM",
- title: "Question Answering System",
- aiTitle: "Question Answering System",
- description:
- "Make a GenAI request to an AI model. Works with many input file types.",
+ top: '34.9306px',
+ left: '902.845px',
+ width: '',
+ height: '',
+ displayName: 'GenAI LLM',
+ title: 'Question Answering System',
+ aiTitle: 'Question Answering System',
+ description: 'Make a GenAI request to an AI model. Works with many input file types.',
},
],
connections: [
{
- sourceId: "CM6JHAW8TNQB",
+ sourceId: 'CM6JHAW8TNQB',
sourceIndex: 3,
- targetId: "CM6QMI3IGUCK",
+ targetId: 'CM6QMI3IGUCK',
targetIndex: 0,
},
{
- sourceId: "CM6JHAW8TNQB",
+ sourceId: 'CM6JHAW8TNQB',
sourceIndex: 4,
- targetId: "CM6QMI3IGUCK",
+ targetId: 'CM6QMI3IGUCK',
targetIndex: 1,
},
{
- sourceId: "CM6QMI3IGUCK",
+ sourceId: 'CM6QMI3IGUCK',
sourceIndex: 0,
- targetId: "CM6JHDY7QJR",
+ targetId: 'CM6JHDY7QJR',
targetIndex: 0,
},
],
diff --git a/packages/runtime/src/core/helpers/agent.helper.ts b/packages/runtime/src/core/helpers/agent.helper.ts
index f5b80380..dba01f33 100644
--- a/packages/runtime/src/core/helpers/agent.helper.ts
+++ b/packages/runtime/src/core/helpers/agent.helper.ts
@@ -1,21 +1,16 @@
-import axios from "axios";
-import config from "../config";
+import axios from 'axios';
+import config from '../config';
-import { Logger } from "@smythos/sre";
+import { Logger } from '@smythos/sre';
-import { includeAuth, mwSysAPI } from "../services/smythAPIReq";
-import { getM2MToken } from "./logto.helper";
+import { includeAuth, mwSysAPI } from '../services/smythAPIReq';
+import { getM2MToken } from './logto.helper';
-import {
- AGENT_AUTH_SETTINGS_KEY,
- MOCK_DATA_SETTINGS_KEY,
- PROD_VERSION_VALUES,
- TEST_VERSION_VALUES,
-} from "@core/constants";
-import { AccessCandidate, ConnectorService } from "@smythos/sre";
-import { defaultFileParsingAgent } from "../default-file-parsing-agent";
+import { AGENT_AUTH_SETTINGS_KEY, MOCK_DATA_SETTINGS_KEY, PROD_VERSION_VALUES, TEST_VERSION_VALUES } from '@core/constants';
+import { AccessCandidate, ConnectorService } from '@smythos/sre';
+import { defaultFileParsingAgent } from '../default-file-parsing-agent';
-const logger = Logger("(Core) Service: Agent Helper");
+const logger = Logger('(Core) Service: Agent Helper');
export function extractAgentVerionsAndPath(url) {
const regex = /^\/v(\d+(\.\d+)?)?(\/api\/.+)/;
@@ -24,33 +19,29 @@ export function extractAgentVerionsAndPath(url) {
if (match) {
return {
path: match[3],
- version: match[1] || "",
+ version: match[1] || '',
};
} else {
return {
path: url,
- version: "",
+ version: '',
};
}
}
export async function getAgentDomainById(agentId: string) {
- const token = (await getM2MToken("https://api.smyth.ai")) as string;
+ const token = (await getM2MToken('https://api.smyth.ai')) as string;
const agentDataConnector = ConnectorService.getAgentDataConnector();
const Authorization = `Bearer ${token}`;
- const result: any = await mwSysAPI
- .get("/domains?verified=true", { headers: { Authorization } })
- .catch((error) => ({ error }));
+ const result: any = await mwSysAPI.get('/domains?verified=true', { headers: { Authorization } }).catch(error => ({ error }));
if (result.error) {
- throw new Error("Error getting domain info");
+ throw new Error('Error getting domain info');
}
- const domain = result.data.domains.find(
- (domainEntry: any) => domainEntry?.aiAgent?.id === agentId
- )?.name;
+ const domain = result.data.domains.find((domainEntry: any) => domainEntry?.aiAgent?.id === agentId)?.name;
if (!domain) {
const deployed = await agentDataConnector.isDeployed(agentId);
@@ -73,9 +64,7 @@ export async function readAgentOAuthConfig(agentData) {
const authOIDCConfigURL = provider.OIDCConfigURL;
const clientID = provider.clientID;
const clientSecret = provider.clientSecret;
- const openid: any = await axios
- .get(authOIDCConfigURL)
- .catch((error) => ({ error }));
+ const openid: any = await axios.get(authOIDCConfigURL).catch(error => ({ error }));
const tokenURL = openid?.data?.token_endpoint;
const authorizationURL = openid?.data?.authorization_endpoint;
@@ -91,13 +80,13 @@ export async function readAgentOAuthConfig(agentData) {
}
export function getAgentIdAndVersion(model: string) {
- const [agentId, version] = model.split("@");
+ const [agentId, version] = model.split('@');
let agentVersion = version?.trim() || undefined;
if (TEST_VERSION_VALUES.includes(agentVersion)) {
- agentVersion = "";
+ agentVersion = '';
}
if (PROD_VERSION_VALUES.includes(agentVersion)) {
- agentVersion = "latest";
+ agentVersion = 'latest';
}
return { agentId, agentVersion };
@@ -105,63 +94,47 @@ export function getAgentIdAndVersion(model: string) {
export async function getAgentEmbodiments(agentID) {
try {
- const token = (await getM2MToken("https://api.smyth.ai")) as string;
- const response = await axios.get(
- `${config.env.MIDDLEWARE_API_BASE_URL}/_sysapi/v1/embodiments?aiAgentId=${agentID}`,
- {
- headers: {
- Authorization: `Bearer ${token}`,
- },
- }
- );
+ const token = (await getM2MToken('https://api.smyth.ai')) as string;
+ const response = await axios.get(`${config.env.MIDDLEWARE_API_BASE_URL}/_sysapi/v1/embodiments?aiAgentId=${agentID}`, {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ });
return response.data.embodiments;
} catch (error: any) {
logger.error(error.response?.data, error.message);
- throw new Error(
- `Error getting embodiments for agentId=${agentID}: ${error?.message}`
- );
+ throw new Error(`Error getting embodiments for agentId=${agentID}: ${error?.message}`);
}
}
-export async function getAgentIdByDomain(domain = "") {
+export async function getAgentIdByDomain(domain = '') {
let agentId;
//first check if this is the internal wildcard agents domain
- const isStageWildcardDomain = domain.includes(
- config.env.DEFAULT_AGENT_DOMAIN
- );
+ const isStageWildcardDomain = domain.includes(config.env.DEFAULT_AGENT_DOMAIN);
const isProdWildcardDomain = domain.includes(config.env.PROD_AGENT_DOMAIN);
if (isStageWildcardDomain || isProdWildcardDomain) {
- agentId = domain.split(".")[0];
- if (
- `${agentId}.${config.env.DEFAULT_AGENT_DOMAIN}` !== domain &&
- `${agentId}.${config.env.PROD_AGENT_DOMAIN}` !== domain
- ) {
+ agentId = domain.split('.')[0];
+ if (`${agentId}.${config.env.DEFAULT_AGENT_DOMAIN}` !== domain && `${agentId}.${config.env.PROD_AGENT_DOMAIN}` !== domain) {
throw new Error(`Invalid agent domain: ${domain}`);
}
if (isStageWildcardDomain) return agentId;
}
- const token = (await getM2MToken("https://api.smyth.ai")) as string;
+ const token = (await getM2MToken('https://api.smyth.ai')) as string;
const Authorization = `Bearer ${token}`;
- const result: any = await mwSysAPI
- .get("/domains?verified=true", { headers: { Authorization } })
- .catch((error) => ({ error }));
+ const result: any = await mwSysAPI.get('/domains?verified=true', { headers: { Authorization } }).catch(error => ({ error }));
if (result.error) {
- throw new Error("Error getting domain info");
+ throw new Error('Error getting domain info');
}
if (agentId) {
- const hasDomain = result.data.domains.find(
- (domainEntry: any) => domainEntry?.aiAgent?.id === agentId
- );
+ const hasDomain = result.data.domains.find((domainEntry: any) => domainEntry?.aiAgent?.id === agentId);
if (hasDomain) {
- throw new Error("Wrong domain");
+ throw new Error('Wrong domain');
}
} else {
- agentId = result.data.domains.find(
- (domainEntry: any) => domainEntry.name === domain
- )?.aiAgent?.id;
+ agentId = result.data.domains.find((domainEntry: any) => domainEntry.name === domain)?.aiAgent?.id;
}
return agentId;
@@ -183,7 +156,7 @@ function migrateAgentData(data) {
return newData;
}
- if (data.version === "1.0.0") {
+ if (data.version === '1.0.0') {
if (data.description && !data.behavior) {
data.behavior = data.description;
}
@@ -194,42 +167,27 @@ function migrateAgentData(data) {
export async function getAgentDataById(agentID, version) {
try {
- const token = (await getM2MToken("https://api.smyth.ai")) as string;
+ const token = (await getM2MToken('https://api.smyth.ai')) as string;
let agentObj;
- const response = await mwSysAPI.get(
- `/ai-agent/${agentID}?include=team.subscription`,
- includeAuth(token)
- );
+ const response = await mwSysAPI.get(`/ai-agent/${agentID}?include=team.subscription`, includeAuth(token));
agentObj = response.data.agent;
const authData = agentObj.data.auth;
- const tasksResponse = await mwSysAPI.get(
- `/quota/team/${agentObj.teamId}/tasks/subscription`,
- includeAuth(token)
- );
+ const tasksResponse = await mwSysAPI.get(`/quota/team/${agentObj.teamId}/tasks/subscription`, includeAuth(token));
agentObj.taskData = tasksResponse.data;
- agentObj.data.debugSessionEnabled =
- agentObj?.data?.debugSessionEnabled && agentObj?.isLocked;
+ agentObj.data.debugSessionEnabled = agentObj?.data?.debugSessionEnabled && agentObj?.isLocked;
if (version) {
- const deploymentsList = await mwSysAPI.get(
- `/ai-agent/${agentID}/deployments`,
- includeAuth(token)
- );
+ const deploymentsList = await mwSysAPI.get(`/ai-agent/${agentID}/deployments`, includeAuth(token));
const deployment =
- version == "latest"
+ version == 'latest'
? deploymentsList?.data?.deployments[0]
- : deploymentsList?.data?.deployments?.find(
- (deployment) => deployment.version === version
- );
+ : deploymentsList?.data?.deployments?.find(deployment => deployment.version === version);
if (deployment) {
- const deployResponse = await mwSysAPI.get(
- `/ai-agent/deployments/${deployment.id}`,
- includeAuth(token)
- );
+ const deployResponse = await mwSysAPI.get(`/ai-agent/deployments/${deployment.id}`, includeAuth(token));
agentObj.data = deployResponse?.data?.deployment?.aiAgentData;
agentObj.data.debugSessionEnabled = false;
agentObj.data.agentVersion = deployment.version;
@@ -238,17 +196,14 @@ export async function getAgentDataById(agentID, version) {
}
}
- if (!agentObj?.data?.auth?.method || agentObj?.data?.auth?.method == "none")
- agentObj.data.auth = authData;
+ if (!agentObj?.data?.auth?.method || agentObj?.data?.auth?.method == 'none') agentObj.data.auth = authData;
agentObj.data = migrateAgentData(agentObj.data);
return agentObj;
} catch (error: any) {
logger.error(error.response?.data, error.message);
- throw new Error(
- `Error getting agent data for agentId=${agentID}: ${error?.message}`
- );
+ throw new Error(`Error getting agent data for agentId=${agentID}: ${error?.message}`);
}
}
@@ -259,20 +214,16 @@ export function addDefaultComponentsAndConnections(agentData) {
async function fetchAgentAuthData(agentId: string) {
const accountConnector = ConnectorService.getAccountConnector();
- return await accountConnector
- .user(AccessCandidate.agent(agentId))
- .getAgentSetting(AGENT_AUTH_SETTINGS_KEY);
+ return await accountConnector.user(AccessCandidate.agent(agentId)).getAgentSetting(AGENT_AUTH_SETTINGS_KEY);
}
export async function getAgentAuthData(agentId: string) {
const freshSettings = await fetchAgentAuthData(agentId);
- return JSON.parse(freshSettings || "{}");
+ return JSON.parse(freshSettings || '{}');
}
export async function getMockData(agentId: string) {
const accountConnector = ConnectorService.getAccountConnector();
- const mockData = await accountConnector
- .user(AccessCandidate.agent(agentId))
- .getAgentSetting(MOCK_DATA_SETTINGS_KEY);
- return JSON.parse(mockData || "{}");
+ const mockData = await accountConnector.user(AccessCandidate.agent(agentId)).getAgentSetting(MOCK_DATA_SETTINGS_KEY);
+ return JSON.parse(mockData || '{}');
}
diff --git a/packages/runtime/src/core/helpers/logto.helper.ts b/packages/runtime/src/core/helpers/logto.helper.ts
index 3fbf055e..faa6d8ad 100644
--- a/packages/runtime/src/core/helpers/logto.helper.ts
+++ b/packages/runtime/src/core/helpers/logto.helper.ts
@@ -3,66 +3,63 @@ import qs from 'querystring';
import config from '../config';
//M2M test
const postData = {
- grant_type: 'client_credentials',
- resource: 'https://default.logto.app/api',
- scope: 'all',
+ grant_type: 'client_credentials',
+ resource: 'https://default.logto.app/api',
+ scope: 'all',
};
const base64Credentials = Buffer.from(`${config.env.LOGTO_M2M_APP_ID}:${config.env.LOGTO_M2M_APP_SECRET}`, 'utf8').toString('base64');
let tokenData = {
- access_token: null,
+ access_token: null,
};
export function getM2MToken(resource?, scope?) {
- return new Promise((resolve, reject) => {
- if (tokenData.access_token) {
- return resolve(tokenData.access_token);
- }
+ return new Promise((resolve, reject) => {
+ if (tokenData.access_token) {
+ return resolve(tokenData.access_token);
+ }
- const body = {
- grant_type: 'client_credentials',
- resource: resource || config.env.LOGTO_API_RESOURCE,
- scope: scope || '',
- };
- axios({
- method: 'post',
- url: `${config.env.LOGTO_SERVER}/oidc/token`,
- headers: {
- Authorization: 'Basic ' + base64Credentials,
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- data: qs.stringify(body),
- })
- .then((response) => {
- tokenData.access_token = response.data.access_token;
- setTimeout(
- () => {
- tokenData.access_token = null;
- },
- (response.data.expires_in - 100) * 1000,
- );
- resolve(tokenData.access_token);
- })
- .catch((error) => {
- reject({ error: error.response.data });
- });
- });
+ const body = {
+ grant_type: 'client_credentials',
+ resource: resource || config.env.LOGTO_API_RESOURCE,
+ scope: scope || '',
+ };
+ axios({
+ method: 'post',
+ url: `${config.env.LOGTO_SERVER}/oidc/token`,
+ headers: {
+ Authorization: 'Basic ' + base64Credentials,
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ data: qs.stringify(body),
+ })
+ .then(response => {
+ tokenData.access_token = response.data.access_token;
+ setTimeout(() => {
+ tokenData.access_token = null;
+ }, (response.data.expires_in - 100) * 1000);
+ resolve(tokenData.access_token);
+ })
+ .catch(error => {
+ reject({ error: error.response.data });
+ });
+ });
}
export async function getUserInfo(userId: string) {
- const token = await getM2MToken('https://default.logto.app/api', 'all');
+ const token = await getM2MToken('https://default.logto.app/api', 'all');
- const response: any = await axios({
- method: 'get',
- url: `${config.env.LOGTO_SERVER}/api/users/${userId}`,
- headers: {
- Authorization: `Bearer ${token}`,
- },
- }).catch((error) => ({ error }));
+ const response: any = await axios({
+ method: 'get',
+ url: `${config.env.LOGTO_SERVER}/api/users/${userId}`,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ }).catch(error => ({ error }));
- if (response.error) {
- return null;
- }
+ if (response.error) {
+ return null;
+ }
- return response.data;
+ return response.data;
}
diff --git a/packages/runtime/src/core/management-router.ts b/packages/runtime/src/core/management-router.ts
index da82a3d1..1eac09c5 100644
--- a/packages/runtime/src/core/management-router.ts
+++ b/packages/runtime/src/core/management-router.ts
@@ -1,7 +1,7 @@
-import express from "express";
-import { app } from "../index.js";
-import { Server } from "http";
-import config from "./config";
+import express from 'express';
+import { app } from '../index.js';
+import { Server } from 'http';
+import config from './config';
const ADMIN_PORT = config.env.ADMIN_PORT || 5054;
const PORT = config.env.PORT || 5053;
@@ -9,7 +9,7 @@ const PORT = config.env.PORT || 5053;
export let server: Server;
-const host = config.env.NODE_ENV === "production" ? "localhost" : "";
+const host = config.env.NODE_ENV === 'production' ? 'localhost' : '';
function enableAppPort() {
if (server && server.listening) {
@@ -27,9 +27,7 @@ function enableAppPort() {
// Function to disable port 5000 to stop accepting new connections
function disableAppPort() {
server.close(() => {
- console.info(
- `App Server listening on port ${PORT} no longer accepting connections`
- );
+ console.info(`App Server listening on port ${PORT} no longer accepting connections`);
});
}
@@ -38,23 +36,23 @@ const managementApp = express();
export { managementApp };
// Route to handle management operations
-managementApp.get("/", (req, res) => {
- res.send("Management operations.");
+managementApp.get('/', (req, res) => {
+ res.send('Management operations.');
});
// Route to enable port 5000 for new connections
-managementApp.get("/enable", (req, res) => {
+managementApp.get('/enable', (req, res) => {
enableAppPort();
res.send(`Port ${PORT} enabled for new connections via management port.`);
});
// Route to disable port 5000 for new connections
-managementApp.get("/disable", (req, res) => {
+managementApp.get('/disable', (req, res) => {
disableAppPort();
res.send(`Port ${PORT} disabled for new connections via management port.`);
});
-managementApp.get("/stats", (req, res) => {
+managementApp.get('/stats', (req, res) => {
server.getConnections((err, count) => {
if (err) {
res.status(500).send(err);
diff --git a/packages/runtime/src/core/middlewares/cors.mw.ts b/packages/runtime/src/core/middlewares/cors.mw.ts
index d4c4d1e5..2dff73fa 100644
--- a/packages/runtime/src/core/middlewares/cors.mw.ts
+++ b/packages/runtime/src/core/middlewares/cors.mw.ts
@@ -1,23 +1,13 @@
-import cors from "cors";
+import cors from 'cors';
-import config from "@core/config";
+import config from '@core/config';
// Minimal CORS - allow everything in development, configurable for production
const corsOptions: cors.CorsOptions = {
- origin:
- process.env.NODE_ENV === "production"
- ? process.env.CORS_ORIGINS?.split(",") || false
- : true,
+ origin: process.env.NODE_ENV === 'production' ? process.env.CORS_ORIGINS?.split(',') || false : true,
credentials: true,
- methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
- allowedHeaders: [
- "Content-Type",
- "Authorization",
- "X-Conversation-Id",
- "X-Auth-Token",
- "X-Parent-Cookie",
- "X-Monitor-Id",
- ],
+ methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
+ allowedHeaders: ['Content-Type', 'Authorization', 'X-Conversation-Id', 'X-Auth-Token', 'X-Parent-Cookie', 'X-Monitor-Id'],
};
export default cors(corsOptions);
diff --git a/packages/runtime/src/core/middlewares/error.mw.ts b/packages/runtime/src/core/middlewares/error.mw.ts
index 725e0a53..e5f4373b 100644
--- a/packages/runtime/src/core/middlewares/error.mw.ts
+++ b/packages/runtime/src/core/middlewares/error.mw.ts
@@ -1,26 +1,21 @@
-import { ErrorRequestHandler, Request, Response, NextFunction } from "express";
-import { Logger } from "@smythos/sre";
+import { ErrorRequestHandler, Request, Response, NextFunction } from 'express';
+import { Logger } from '@smythos/sre';
-import config from "@core/config";
+import config from '@core/config';
-const logger = Logger("(Core) Middleware: Error");
+const logger = Logger('(Core) Middleware: Error');
/**
* Centralized error handler for all application errors
*/
-const errorHandler: ErrorRequestHandler = (
- err: any,
- req: Request,
- res: Response,
- _next: NextFunction
-) => {
+const errorHandler: ErrorRequestHandler = (err: any, req: Request, res: Response, _next: NextFunction) => {
// eslint-disable-next-line prefer-const
let { statusCode, message, errKey } = err;
// Handle operational vs programming errors
if (!err.isOperational) {
statusCode = 500;
- message = "Internal Server Error";
+ message = 'Internal Server Error';
}
res.locals.errorMessage = err.message;
@@ -28,23 +23,20 @@ const errorHandler: ErrorRequestHandler = (
const response = {
success: false,
code: statusCode ?? 500,
- message: message ?? "Internal Server Error",
- ...(config.env.NODE_ENV === "development" && { stack: err.stack }),
+ message: message ?? 'Internal Server Error',
+ ...(config.env.NODE_ENV === 'development' && { stack: err.stack }),
...(errKey && { errKey }),
};
// Log error with request context
- logger.error(
- `[${statusCode ?? 500}] ${req.method} ${req.path} - ${message}`,
- {
- statusCode: statusCode ?? 500,
- method: req.method,
- path: req.path,
- userAgent: req.get("User-Agent"),
- ip: req.ip,
- ...(config.env.NODE_ENV === "development" && { stack: err.stack }),
- }
- );
+ logger.error(`[${statusCode ?? 500}] ${req.method} ${req.path} - ${message}`, {
+ statusCode: statusCode ?? 500,
+ method: req.method,
+ path: req.path,
+ userAgent: req.get('User-Agent'),
+ ip: req.ip,
+ ...(config.env.NODE_ENV === 'development' && { stack: err.stack }),
+ });
return res.status(statusCode ?? 500).json(response);
};
@@ -52,11 +44,7 @@ const errorHandler: ErrorRequestHandler = (
/**
* 404 Not Found handler - creates error and passes to error handler
*/
-const notFoundHandler = (
- req: Request,
- res: Response,
- next: NextFunction
-): void => {
+const notFoundHandler = (req: Request, res: Response, next: NextFunction): void => {
const error = new Error(`Path not found: ${req.method} ${req.path}`);
(error as any).statusCode = 404;
(error as any).isOperational = true;
diff --git a/packages/runtime/src/core/middlewares/rateLimiter.mw.ts b/packages/runtime/src/core/middlewares/rateLimiter.mw.ts
index 1727a786..8c264b9c 100644
--- a/packages/runtime/src/core/middlewares/rateLimiter.mw.ts
+++ b/packages/runtime/src/core/middlewares/rateLimiter.mw.ts
@@ -1,9 +1,9 @@
-import { Request, Response, NextFunction } from "express";
-import { Logger } from "@smythos/sre";
+import { Request, Response, NextFunction } from 'express';
+import { Logger } from '@smythos/sre';
-import config from "@core/config";
+import config from '@core/config';
-const console = Logger("(Core) Middleware: RateLimiter");
+const console = Logger('(Core) Middleware: RateLimiter');
// Configuration from environment variables with sensible defaults
const REQUESTS_PER_MINUTE = config.env.REQ_LIMIT_PER_MINUTE as number;
@@ -30,14 +30,14 @@ const concurrentStore = new Map<string, ConcurrentEntry>();
*/
const shouldExcludeIP = (ip: string): boolean => {
const excludedPrefixes = [
- "127.0.0.1", // localhost IPv4
- "::1", // localhost IPv6
- "10.20.", // internal network
- "10.30.", // internal network
- "192.168.", // private network
- "172.16.", // private network
+ '127.0.0.1', // localhost IPv4
+ '::1', // localhost IPv6
+ '10.20.', // internal network
+ '10.30.', // internal network
+ '192.168.', // private network
+ '172.16.', // private network
];
- return excludedPrefixes.some((prefix) => ip.startsWith(prefix));
+ return excludedPrefixes.some(prefix => ip.startsWith(prefix));
};
/**
@@ -49,9 +49,7 @@ const cleanupExpiredEntries = (): void => {
// Cleanup rate limit entries
for (const [key, entry] of rateLimitStore.entries()) {
if (now - entry.lastCleanup > CLEANUP_INTERVAL_MS) {
- entry.requests = entry.requests.filter(
- (timestamp) => now - timestamp < WINDOW_SIZE_MS
- );
+ entry.requests = entry.requests.filter(timestamp => now - timestamp < WINDOW_SIZE_MS);
entry.lastCleanup = now;
if (entry.requests.length === 0) {
@@ -86,9 +84,7 @@ const checkRateLimit = (clientIP: string): boolean => {
}
// Clean up old requests
- entry.requests = entry.requests.filter(
- (timestamp) => now - timestamp < WINDOW_SIZE_MS
- );
+ entry.requests = entry.requests.filter(timestamp => now - timestamp < WINDOW_SIZE_MS);
if (entry.requests.length >= REQUESTS_PER_MINUTE) {
return true; // Rate limit exceeded
@@ -110,7 +106,7 @@ const checkConcurrentRequests = (clientIP: string): (() => void) | null => {
const currentCount = entry?.count || 0;
if (currentCount >= MAX_CONCURRENT_REQUESTS) {
- throw new Error("Concurrent limit exceeded");
+ throw new Error('Concurrent limit exceeded');
}
// Increment counter
@@ -144,7 +140,7 @@ setInterval(cleanupExpiredEntries, CLEANUP_INTERVAL_MS);
*/
const RateLimiter = (req: Request, res: Response, next: NextFunction): void => {
try {
- const clientIP = req.ip || req.connection.remoteAddress || "unknown";
+ const clientIP = req.ip || req.connection.remoteAddress || 'unknown';
// Skip rate limiting for excluded IPs (localhost, private networks)
if (shouldExcludeIP(clientIP)) {
@@ -155,8 +151,8 @@ const RateLimiter = (req: Request, res: Response, next: NextFunction): void => {
if (checkRateLimit(clientIP)) {
console.log(`Rate limit exceeded for IP: ${clientIP}`);
res.status(429).json({
- error: "Too Many Requests",
- message: "Rate limit exceeded. Please try again later.",
+ error: 'Too Many Requests',
+ message: 'Rate limit exceeded. Please try again later.',
retryAfter: Math.ceil(WINDOW_SIZE_MS / 1000), // seconds until window resets
});
return;
@@ -167,11 +163,11 @@ const RateLimiter = (req: Request, res: Response, next: NextFunction): void => {
try {
cleanupConcurrent = checkConcurrentRequests(clientIP);
} catch (err) {
- if (err.message === "Concurrent limit exceeded") {
+ if (err.message === 'Concurrent limit exceeded') {
console.log(`Concurrent request limit exceeded for IP: ${clientIP}`);
res.status(429).json({
- error: "Too Many Requests",
- message: "Too many concurrent requests. Please try again later.",
+ error: 'Too Many Requests',
+ message: 'Too many concurrent requests. Please try again later.',
});
return;
}
@@ -181,20 +177,20 @@ const RateLimiter = (req: Request, res: Response, next: NextFunction): void => {
// Set up cleanup for concurrent requests if needed
if (cleanupConcurrent) {
const cleanup = () => {
- res.removeListener("finish", cleanup);
- res.removeListener("close", cleanup);
- res.removeListener("error", cleanup);
+ res.removeListener('finish', cleanup);
+ res.removeListener('close', cleanup);
+ res.removeListener('error', cleanup);
cleanupConcurrent();
};
- res.on("finish", cleanup);
- res.on("close", cleanup);
- res.on("error", cleanup);
+ res.on('finish', cleanup);
+ res.on('close', cleanup);
+ res.on('error', cleanup);
}
next();
} catch (err) {
- console.error("Unexpected error in rate limiter:", err);
+ console.error('Unexpected error in rate limiter:', err);
// Don't block requests on unexpected errors
next();
}
diff --git a/packages/runtime/src/core/middlewares/uploadHandler.mw.ts b/packages/runtime/src/core/middlewares/uploadHandler.mw.ts
index cfa5df5f..2ef3ca20 100644
--- a/packages/runtime/src/core/middlewares/uploadHandler.mw.ts
+++ b/packages/runtime/src/core/middlewares/uploadHandler.mw.ts
@@ -1,5 +1,5 @@
-import multer from "multer";
-import { MAX_FILE_SIZE, MAX_FILE_COUNT } from "@core/constants";
+import multer from 'multer';
+import { MAX_FILE_SIZE, MAX_FILE_COUNT } from '@core/constants';
const upload = multer({
limits: { fileSize: MAX_FILE_SIZE },
@@ -7,13 +7,13 @@ const upload = multer({
});
export function uploadHandler(req, res, next) {
- upload.any()(req, res, (err) => {
+ upload.any()(req, res, err => {
if (err) {
return next(new Error(`File upload error: ${err.message}`));
}
if (req.files && req.files.length > MAX_FILE_COUNT) {
- return res.status(400).send("Too many files");
+ return res.status(400).send('Too many files');
}
next();
diff --git a/packages/runtime/src/core/middlewares/userAgentAccessCheck.mw.ts b/packages/runtime/src/core/middlewares/userAgentAccessCheck.mw.ts
index ac233cb7..204e6df2 100644
--- a/packages/runtime/src/core/middlewares/userAgentAccessCheck.mw.ts
+++ b/packages/runtime/src/core/middlewares/userAgentAccessCheck.mw.ts
@@ -1,43 +1,39 @@
-import { ConnectorService, Logger } from "@smythos/sre";
-import { mwUserAPI } from "@core/services/smythAPIReq";
+import { ConnectorService, Logger } from '@smythos/sre';
+import { mwUserAPI } from '@core/services/smythAPIReq';
-const console = Logger("(Core) Middleware: User Agent Access Check");
+const console = Logger('(Core) Middleware: User Agent Access Check');
export default async function UserAgentAccessCheck(req, res, next) {
const agentDataConnector = ConnectorService.getAgentDataConnector();
- let agentId = req.header("X-AGENT-ID");
- const accessToken = req.header("Authorization")
- ? req.header("Authorization").split(" ")[1]
- : null;
+ let agentId = req.header('X-AGENT-ID');
+ const accessToken = req.header('Authorization') ? req.header('Authorization').split(' ')[1] : null;
if (!accessToken) {
- return res.status(401).send({ error: "Unauthorized" });
+ return res.status(401).send({ error: 'Unauthorized' });
}
if (!agentId) {
const domain = req.hostname;
- agentId = await agentDataConnector
- .getAgentIdByDomain(domain)
- .catch((error) => {
- console.error(error);
- });
+ agentId = await agentDataConnector.getAgentIdByDomain(domain).catch(error => {
+ console.error(error);
+ });
}
const agent = await mwUserAPI
.get(`/ai-agent/${agentId}`, {
headers: {
Authorization: `Bearer ${accessToken}`,
- "x-smyth-team-id": req.header("x-smyth-team-id") ?? undefined,
+ 'x-smyth-team-id': req.header('x-smyth-team-id') ?? undefined,
},
})
- .catch((err) => {
+ .catch(err => {
console.error(err);
return false;
});
if (!agent) {
- return res.status(401).send({ error: "Unauthorized" });
+ return res.status(401).send({ error: 'Unauthorized' });
}
next();
}
diff --git a/packages/runtime/src/core/middlewares/validate.mw.ts b/packages/runtime/src/core/middlewares/validate.mw.ts
index 6360ee41..55773c98 100644
--- a/packages/runtime/src/core/middlewares/validate.mw.ts
+++ b/packages/runtime/src/core/middlewares/validate.mw.ts
@@ -3,37 +3,37 @@ import Joi, { ObjectSchema, Schema } from 'joi';
import ApiError from '../utils/apiError';
type AnyObject = {
- [x: string]: any;
+ [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;
- }, {});
+ 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;
+ }, {});
type SchemaObject = {
- body?: ObjectSchema<any> | Schema;
- query?: ObjectSchema<any> | Schema;
- params?: ObjectSchema<any> | Schema;
+ 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);
+ 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(400, errorMessage));
- }
- Object.assign(req, value);
- return next();
+ if (error) {
+ const errorMessage = error.details.map(details => details.message).join(', ');
+ return next(new ApiError(400, errorMessage));
+ }
+ Object.assign(req, value);
+ return next();
};
export { validate };
diff --git a/packages/runtime/src/core/router-config.ts b/packages/runtime/src/core/router-config.ts
index f601d889..198610ac 100644
--- a/packages/runtime/src/core/router-config.ts
+++ b/packages/runtime/src/core/router-config.ts
@@ -1,30 +1,23 @@
-import { Express } from "express";
+import { Express } from 'express';
-import { uploadHandler } from "@core/middlewares/uploadHandler.mw";
+import { uploadHandler } from '@core/middlewares/uploadHandler.mw';
-import agentRunnerAgentLoader from "@agent-runner/middlewares/agentLoader.mw";
-import agentRunnerOauthRouter from "@agent-runner/routes/_oauth/router";
-import { processAgentRequest as agentRunnerProcessAgentRequest } from "@agent-runner/services/agent-request-handler";
+import agentRunnerAgentLoader from '@agent-runner/middlewares/agentLoader.mw';
+import agentRunnerOauthRouter from '@agent-runner/routes/_oauth/router';
+import { processAgentRequest as agentRunnerProcessAgentRequest } from '@agent-runner/services/agent-request-handler';
-import debuggerAgentLoader from "@debugger/middlewares/agentLoader.mw";
-import modelsRouter from "@debugger/routes/models/router";
+import debuggerAgentLoader from '@debugger/middlewares/agentLoader.mw';
+import modelsRouter from '@debugger/routes/models/router';
import {
createSseConnection as debuggerCreateSseConnection,
getDebugSession as debuggerGetDebugSession,
processAgentRequest as debuggerProcessAgentRequest,
-} from "@debugger/services/agent-request-handler";
+} from '@debugger/services/agent-request-handler';
-import {
- RuntimeConfig,
- loadRuntimeConfig,
- validateRuntimeConfig,
-} from "./runtime-config";
-import {
- createAgentRunnerRouter,
- createDebuggerRouter,
-} from "./shared-agent-router";
-import { createConfiguredSmartRouter } from "./smart-agent-router";
-import config from "./config";
+import { RuntimeConfig, loadRuntimeConfig, validateRuntimeConfig } from './runtime-config';
+import { createAgentRunnerRouter, createDebuggerRouter } from './shared-agent-router';
+import { createConfiguredSmartRouter } from './smart-agent-router';
+import config from './config';
/**
* Configures and mounts agent routers based on runtime configuration
@@ -36,18 +29,13 @@ import config from "./config";
* - 'agent-runner': Only agent-runner service
* - 'embodiment': Only embodiment service
*/
-export function configureAgentRouters(
- app: Express,
- runtimeConfig?: RuntimeConfig
-) {
+export function configureAgentRouters(app: Express, runtimeConfig?: RuntimeConfig) {
const config = runtimeConfig || loadRuntimeConfig();
// Validate configuration
const validation = validateRuntimeConfig(config);
if (!validation.valid) {
- throw new Error(
- `Invalid runtime configuration: ${validation.errors.join(", ")}`
- );
+ throw new Error(`Invalid runtime configuration: ${validation.errors.join(', ')}`);
}
console.log(`Configuring ${config.serverType} server with services:`, {
@@ -58,8 +46,8 @@ export function configureAgentRouters(
});
// Mount common routes that should be available in all server configurations
- console.log("Mounting /models route (available for all server types)");
- app.use("/models", modelsRouter);
+ console.log('Mounting /models route (available for all server types)');
+ app.use('/models', modelsRouter);
// Configure based on routing strategy and enabled services
const debuggerEnabled = config.services.debugger.enabled;
@@ -67,12 +55,8 @@ export function configureAgentRouters(
const embodimentEnabled = config.services.embodiment.enabled;
// Smart routing: Multiple services with intelligent request routing
- if (
- config.routing.strategy === "smart" &&
- debuggerEnabled &&
- agentRunnerEnabled
- ) {
- console.log("Using smart router for intelligent request routing");
+ if (config.routing.strategy === 'smart' && debuggerEnabled && agentRunnerEnabled) {
+ console.log('Using smart router for intelligent request routing');
const smartRouter = createConfiguredSmartRouter(
{
@@ -90,42 +74,32 @@ export function configureAgentRouters(
{
enableMetrics: config.server.metrics,
enableDebuggerRoutes: debuggerEnabled,
- }
+ },
);
- app.use("/", smartRouter);
+ app.use('/', smartRouter);
return;
}
// Separate routing: Mount individual routers (extraction-ready)
- if (
- config.routing.strategy === "separate" ||
- config.routing.strategy === "smart"
- ) {
+ if (config.routing.strategy === 'separate' || config.routing.strategy === 'smart') {
if (debuggerEnabled) {
- console.log("Mounting debugger router");
- const debuggerRouter = createDebuggerRouter(
- [uploadHandler, debuggerAgentLoader],
- debuggerProcessAgentRequest,
- {
- getDebugSession: debuggerGetDebugSession,
- createSseConnection: debuggerCreateSseConnection,
- }
- );
- app.use("/", debuggerRouter);
+ console.log('Mounting debugger router');
+ const debuggerRouter = createDebuggerRouter([uploadHandler, debuggerAgentLoader], debuggerProcessAgentRequest, {
+ getDebugSession: debuggerGetDebugSession,
+ createSseConnection: debuggerCreateSseConnection,
+ });
+ app.use('/', debuggerRouter);
}
if (agentRunnerEnabled) {
- console.log("Mounting agent-runner router");
- const agentRunnerRouter = createAgentRunnerRouter(
- [uploadHandler, agentRunnerAgentLoader],
- agentRunnerProcessAgentRequest
- );
- app.use("/", agentRunnerRouter);
+ console.log('Mounting agent-runner router');
+ const agentRunnerRouter = createAgentRunnerRouter([uploadHandler, agentRunnerAgentLoader], agentRunnerProcessAgentRequest);
+ app.use('/', agentRunnerRouter);
// Mount agent-runner-specific routes
- console.log("Mounting /oauth route for agent-runner");
- app.use("/oauth", agentRunnerOauthRouter);
+ console.log('Mounting /oauth route for agent-runner');
+ app.use('/oauth', agentRunnerOauthRouter);
}
// Note: Embodiment router will be mounted here when embodimentEnabled is true
@@ -133,23 +107,19 @@ export function configureAgentRouters(
}
// Legacy routing: Use original individual routers (for backward compatibility)
- if (config.routing.strategy === "legacy") {
- console.log("Using legacy routing with original routers");
+ if (config.routing.strategy === 'legacy') {
+ console.log('Using legacy routing with original routers');
if (debuggerEnabled) {
- import("@debugger/routes/agent/routes").then(
- ({ default: debuggerRouter }) => {
- app.use("/", debuggerRouter);
- }
- );
+ import('@debugger/routes/agent/routes').then(({ default: debuggerRouter }) => {
+ app.use('/', debuggerRouter);
+ });
}
if (agentRunnerEnabled) {
- import("@agent-runner/routes/agent/router").then(
- ({ default: agentRunnerRouter }) => {
- app.use("/", agentRunnerRouter);
- }
- );
+ import('@agent-runner/routes/agent/router').then(({ default: agentRunnerRouter }) => {
+ app.use('/', agentRunnerRouter);
+ });
}
}
}
@@ -162,16 +132,16 @@ export function configureAgentRouters(
// For backward compatibility - these functions now return RuntimeConfig
export function createDebuggerServerConfig(): RuntimeConfig {
return {
- serverType: "debugger",
+ serverType: 'debugger',
services: {
debugger: { enabled: true, standalone: true },
agentRunner: { enabled: false, standalone: false },
embodiment: { enabled: false, standalone: false },
},
- routing: { strategy: "separate" },
+ routing: { strategy: 'separate' },
server: {
port: config.env.PORT,
- name: "smythos-debugger-server",
+ name: 'smythos-debugger-server',
healthCheck: true,
metrics: true,
},
@@ -186,16 +156,16 @@ export function createDebuggerServerConfig(): RuntimeConfig {
export function createAgentRunnerServerConfig(): RuntimeConfig {
return {
- serverType: "agent-runner",
+ serverType: 'agent-runner',
services: {
debugger: { enabled: false, standalone: false },
agentRunner: { enabled: true, standalone: true },
embodiment: { enabled: false, standalone: false },
},
- routing: { strategy: "separate" },
+ routing: { strategy: 'separate' },
server: {
port: config.env.PORT,
- name: "smythos-agent-runner-server",
+ name: 'smythos-agent-runner-server',
healthCheck: true,
metrics: true,
},
@@ -210,16 +180,16 @@ export function createAgentRunnerServerConfig(): RuntimeConfig {
export function createEmbodimentServerConfig(): RuntimeConfig {
return {
- serverType: "embodiment",
+ serverType: 'embodiment',
services: {
debugger: { enabled: false, standalone: false },
agentRunner: { enabled: false, standalone: false },
embodiment: { enabled: true, standalone: true },
},
- routing: { strategy: "separate" },
+ routing: { strategy: 'separate' },
server: {
port: config.env.PORT,
- name: "smythos-embodiment-server",
+ name: 'smythos-embodiment-server',
healthCheck: true,
metrics: true,
},
@@ -234,16 +204,16 @@ export function createEmbodimentServerConfig(): RuntimeConfig {
export function createCombinedServerConfig(): RuntimeConfig {
return {
- serverType: "combined",
+ serverType: 'combined',
services: {
debugger: { enabled: true, standalone: false },
agentRunner: { enabled: true, standalone: false },
embodiment: { enabled: true, standalone: false },
},
- routing: { strategy: "smart" },
+ routing: { strategy: 'smart' },
server: {
port: config.env.PORT,
- name: "smythos-runtime-combined",
+ name: 'smythos-runtime-combined',
healthCheck: true,
metrics: true,
},
diff --git a/packages/runtime/src/core/routing/types.ts b/packages/runtime/src/core/routing/types.ts
index b4bf13de..a1ed2ad5 100644
--- a/packages/runtime/src/core/routing/types.ts
+++ b/packages/runtime/src/core/routing/types.ts
@@ -3,7 +3,7 @@
* Following Domain-Driven Design and Clean Architecture principles
*/
-import { Request } from "express";
+import { Request } from 'express';
export interface AgentContext {
id: string;
diff --git a/packages/runtime/src/core/runtime-config.ts b/packages/runtime/src/core/runtime-config.ts
index 7143eb7c..be6d19a4 100644
--- a/packages/runtime/src/core/runtime-config.ts
+++ b/packages/runtime/src/core/runtime-config.ts
@@ -1,4 +1,4 @@
-import config from "./config";
+import config from './config';
/**
* Runtime Configuration System
* Designed for future server extraction without code changes
@@ -6,7 +6,7 @@ import config from "./config";
export interface RuntimeConfig {
// Server identity - determines which services this instance provides
- serverType: "combined" | "debugger" | "agent-runner" | "embodiment";
+ serverType: 'combined' | 'debugger' | 'agent-runner' | 'embodiment';
// Service enablement flags
services: {
@@ -26,7 +26,7 @@ export interface RuntimeConfig {
// Routing strategy when multiple services are enabled
routing: {
- strategy: "smart" | "separate" | "legacy";
+ strategy: 'smart' | 'separate' | 'legacy';
// Smart: Intelligent routing based on request characteristics
// Separate: Mount separate routers (current approach)
// Legacy: Use original individual routers
@@ -55,16 +55,16 @@ export interface RuntimeConfig {
export const RuntimeConfigs = {
// Combined server (current default)
combined: (): RuntimeConfig => ({
- serverType: "combined",
+ serverType: 'combined',
services: {
debugger: { enabled: true, standalone: false },
agentRunner: { enabled: true, standalone: false },
embodiment: { enabled: true, standalone: false },
},
- routing: { strategy: "smart" },
+ routing: { strategy: 'smart' },
server: {
port: 5000,
- name: "smythos-runtime-combined",
+ name: 'smythos-runtime-combined',
healthCheck: true,
metrics: true,
},
@@ -78,16 +78,16 @@ export const RuntimeConfigs = {
// Debugger-only server (for extraction)
debugger: (): RuntimeConfig => ({
- serverType: "debugger",
+ serverType: 'debugger',
services: {
debugger: { enabled: true, standalone: true },
agentRunner: { enabled: false, standalone: false },
embodiment: { enabled: false, standalone: false },
},
- routing: { strategy: "separate" },
+ routing: { strategy: 'separate' },
server: {
port: 5001,
- name: "smythos-debugger-server",
+ name: 'smythos-debugger-server',
healthCheck: true,
metrics: true,
},
@@ -101,16 +101,16 @@ export const RuntimeConfigs = {
// Agent-runner-only server (for extraction)
agentRunner: (): RuntimeConfig => ({
- serverType: "agent-runner",
+ serverType: 'agent-runner',
services: {
debugger: { enabled: false, standalone: false },
agentRunner: { enabled: true, standalone: true },
embodiment: { enabled: false, standalone: false },
},
- routing: { strategy: "separate" },
+ routing: { strategy: 'separate' },
server: {
port: 5002,
- name: "smythos-agent-runner-server",
+ name: 'smythos-agent-runner-server',
healthCheck: true,
metrics: true,
},
@@ -124,16 +124,16 @@ export const RuntimeConfigs = {
// Embodiment-only server (for extraction)
embodiment: (): RuntimeConfig => ({
- serverType: "embodiment",
+ serverType: 'embodiment',
services: {
debugger: { enabled: false, standalone: false },
agentRunner: { enabled: false, standalone: false },
embodiment: { enabled: true, standalone: true },
},
- routing: { strategy: "separate" },
+ routing: { strategy: 'separate' },
server: {
port: 5003,
- name: "smythos-embodiment-server",
+ name: 'smythos-embodiment-server',
healthCheck: true,
metrics: true,
},
@@ -154,13 +154,13 @@ export function loadRuntimeConfig(): RuntimeConfig {
const configType = config.env.SMYTHOS_SERVER_TYPE;
switch (configType) {
- case "debugger":
+ case 'debugger':
return RuntimeConfigs.debugger();
- case "agent-runner":
+ case 'agent-runner':
return RuntimeConfigs.agentRunner();
- case "embodiment":
+ case 'embodiment':
return RuntimeConfigs.embodiment();
- case "combined":
+ case 'combined':
default:
return RuntimeConfigs.combined();
}
@@ -176,11 +176,9 @@ export function validateRuntimeConfig(config: RuntimeConfig): {
const errors: string[] = [];
// At least one service must be enabled
- const enabledServices = Object.values(config.services).filter(
- (service) => service.enabled
- );
+ const enabledServices = Object.values(config.services).filter(service => service.enabled);
if (enabledServices.length === 0) {
- errors.push("At least one service must be enabled");
+ errors.push('At least one service must be enabled');
}
// Standalone services should be the only enabled service
@@ -189,11 +187,7 @@ export function validateRuntimeConfig(config: RuntimeConfig): {
.map(([name, _]) => name);
if (standaloneServices.length > 1) {
- errors.push(
- `Multiple standalone services not allowed: ${standaloneServices.join(
- ", "
- )}`
- );
+ errors.push(`Multiple standalone services not allowed: ${standaloneServices.join(', ')}`);
}
if (standaloneServices.length === 1) {
@@ -202,17 +196,13 @@ export function validateRuntimeConfig(config: RuntimeConfig): {
.map(([name, _]) => name);
if (otherEnabledServices.length > 0) {
- errors.push(
- `Standalone service cannot coexist with other services: ${otherEnabledServices.join(
- ", "
- )}`
- );
+ errors.push(`Standalone service cannot coexist with other services: ${otherEnabledServices.join(', ')}`);
}
}
// Smart routing requires multiple services
- if (config.routing.strategy === "smart" && enabledServices.length < 2) {
- errors.push("Smart routing requires multiple enabled services");
+ if (config.routing.strategy === 'smart' && enabledServices.length < 2) {
+ errors.push('Smart routing requires multiple enabled services');
}
return {
diff --git a/packages/runtime/src/core/services/request-context.ts b/packages/runtime/src/core/services/request-context.ts
index 5268b56c..0a42aee6 100644
--- a/packages/runtime/src/core/services/request-context.ts
+++ b/packages/runtime/src/core/services/request-context.ts
@@ -3,20 +3,20 @@ import { AsyncLocalStorage } from 'async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();
export const requestContext = {
- run: (callback, initialValue = {}) => {
- asyncLocalStorage.run(initialValue, callback);
- },
- get: (key: string) => {
- const store = asyncLocalStorage.getStore();
- if (store) {
- return store[key];
- }
- return null;
- },
- set: (key: string, value: any) => {
- const store = asyncLocalStorage.getStore();
- if (store) {
- store[key] = value;
- }
- },
+ run: (callback, initialValue = {}) => {
+ asyncLocalStorage.run(initialValue, callback);
+ },
+ get: (key: string) => {
+ const store = asyncLocalStorage.getStore();
+ if (store) {
+ return store[key];
+ }
+ return null;
+ },
+ set: (key: string, value: any) => {
+ const store = asyncLocalStorage.getStore();
+ if (store) {
+ store[key] = value;
+ }
+ },
};
diff --git a/packages/runtime/src/core/services/smythAPIReq.ts b/packages/runtime/src/core/services/smythAPIReq.ts
index d7f55245..cde93be5 100644
--- a/packages/runtime/src/core/services/smythAPIReq.ts
+++ b/packages/runtime/src/core/services/smythAPIReq.ts
@@ -1,5 +1,5 @@
-import axios from "axios";
-import config from "../config";
+import axios from 'axios';
+import config from '../config';
//middleware sys API
export const mwSysAPI = axios.create({
@@ -22,14 +22,12 @@ export function includeAuth(token: string) {
* @param authHeader - The Authorization header value
* @returns The extracted token or null if the token is invalid
*/
-export const extractBearerToken = (
- authHeader: string | undefined
-): string | null => {
+export const extractBearerToken = (authHeader: string | undefined): string | null => {
if (!authHeader) {
return null;
}
- if (typeof authHeader !== "string" || !authHeader.startsWith("Bearer ")) {
+ if (typeof authHeader !== 'string' || !authHeader.startsWith('Bearer ')) {
return null;
}
diff --git a/packages/runtime/src/core/shared-agent-router.ts b/packages/runtime/src/core/shared-agent-router.ts
index 122a1cfa..e321046c 100644
--- a/packages/runtime/src/core/shared-agent-router.ts
+++ b/packages/runtime/src/core/shared-agent-router.ts
@@ -1,8 +1,8 @@
-import { Logger } from "@smythos/sre";
-import express from "express";
+import { Logger } from '@smythos/sre';
+import express from 'express';
export interface AgentRouterConfig {
- mode: "debugger" | "agent-runner";
+ mode: 'debugger' | 'agent-runner';
middlewares: express.RequestHandler[];
processAgentRequest: (agentOrId: any, req: express.Request) => Promise<any>;
additionalRoutes?: (router: express.Router) => void;
@@ -14,7 +14,7 @@ export interface AgentRouterConfig {
* This allows code reuse while maintaining the ability to extract servers separately
*/
export function createAgentRouter(config: AgentRouterConfig): express.Router {
- const console = Logger(config.loggerPrefix || "[Shared] Router: Agent");
+ const console = Logger(config.loggerPrefix || '[Shared] Router: Agent');
const router = express.Router();
// Add any additional routes specific to the mode (e.g., debugger's /debugSession and /monitor)
@@ -24,11 +24,11 @@ export function createAgentRouter(config: AgentRouterConfig): express.Router {
// Common API routes with configurable middleware and processing
const apiRoutes = [
- { method: "post", path: "/api/*" },
- { method: "get", path: "/api/*" },
- { method: "post", path: "/:version/api/*" },
- { method: "get", path: "/:version/api/*" },
- { method: "post", path: /^\/v[0-9]+(\.[0-9]+)?\/api\/(.+)/ },
+ { method: 'post', path: '/api/*' },
+ { method: 'get', path: '/api/*' },
+ { method: 'post', path: '/:version/api/*' },
+ { method: 'get', path: '/:version/api/*' },
+ { method: 'post', path: /^\/v[0-9]+(\.[0-9]+)?\/api\/(.+)/ },
];
apiRoutes.forEach(({ method, path }) => {
@@ -36,12 +36,12 @@ export function createAgentRouter(config: AgentRouterConfig): express.Router {
try {
const agent = req._agent;
if (!agent) {
- return res.status(404).json({ error: "Agent not found" });
+ return res.status(404).json({ error: 'Agent not found' });
}
// Handle different function signatures based on mode
let result: any;
- if (config.mode === "debugger") {
+ if (config.mode === 'debugger') {
// Debugger mode: pass agent.id as first parameter
result = await config.processAgentRequest(agent.id, req);
} else {
@@ -51,8 +51,8 @@ export function createAgentRouter(config: AgentRouterConfig): express.Router {
return res.status(result?.status || 500).send(result?.data);
} catch (error) {
- console.error("Error processing agent request:", error);
- return res.status(500).json({ error: "Internal Server Error" });
+ console.error('Error processing agent request:', error);
+ return res.status(500).json({ error: 'Internal Server Error' });
}
});
});
@@ -69,34 +69,34 @@ export function createDebuggerRouter(
additionalServices?: {
getDebugSession: (id: string) => any;
createSseConnection: (req: any) => string;
- }
+ },
): express.Router {
return createAgentRouter({
- mode: "debugger",
+ mode: 'debugger',
middlewares,
processAgentRequest,
- loggerPrefix: "[Debugger] Router: Agent",
- additionalRoutes: (router) => {
+ loggerPrefix: '[Debugger] Router: Agent',
+ additionalRoutes: router => {
// Additional routes are now mounted directly in router-config.ts
if (additionalServices) {
// Debug session route
- router.get("/agent/:id/debugSession", (req, res) => {
+ router.get('/agent/:id/debugSession', (req, res) => {
console.log(
- `Getting debug session for agent ${req.params.id} with client IP ${req.headers["x-forwarded-for"]} - ${req.socket.remoteAddress}. x-hash-id ${req.headers["x-hash-id"]}`
+ `Getting debug session for agent ${req.params.id} with client IP ${req.headers['x-forwarded-for']} - ${req.socket.remoteAddress}. x-hash-id ${req.headers['x-hash-id']}`,
);
const dbgSession = additionalServices.getDebugSession(req.params.id);
res.send({ dbgSession });
});
// Monitor route (SSE)
- router.get("/agent/:id/monitor", (req, res) => {
+ router.get('/agent/:id/monitor', (req, res) => {
const sseId = additionalServices.createSseConnection(req);
// Set headers for SSE
- res.setHeader("Content-Type", "text/event-stream");
- res.setHeader("Cache-Control", "no-cache");
- res.setHeader("Connection", "keep-alive");
+ res.setHeader('Content-Type', 'text/event-stream');
+ res.setHeader('Cache-Control', 'no-cache');
+ res.setHeader('Connection', 'keep-alive');
// Send the unique ID as the first event
res.write(`event: init\n`);
@@ -112,14 +112,14 @@ export function createDebuggerRouter(
*/
export function createAgentRunnerRouter(
middlewares: express.RequestHandler[],
- processAgentRequest: (agent: any, req: express.Request) => Promise<any>
+ processAgentRequest: (agent: any, req: express.Request) => Promise<any>,
): express.Router {
return createAgentRouter({
- mode: "agent-runner",
+ mode: 'agent-runner',
middlewares,
processAgentRequest,
- loggerPrefix: "(Agent Runner) Router: Agent",
- additionalRoutes: (router) => {
+ loggerPrefix: '(Agent Runner) Router: Agent',
+ additionalRoutes: router => {
// Additional routes are now mounted directly in router-config.ts
},
});
diff --git a/packages/runtime/src/core/smart-agent-router.ts b/packages/runtime/src/core/smart-agent-router.ts
index 0efa239d..edb0eef1 100644
--- a/packages/runtime/src/core/smart-agent-router.ts
+++ b/packages/runtime/src/core/smart-agent-router.ts
@@ -4,20 +4,17 @@
*
*/
-import { Logger } from "@smythos/sre";
-import express from "express";
-import { v4 as uuidv4 } from "uuid";
+import { Logger } from '@smythos/sre';
+import express from 'express';
+import { v4 as uuidv4 } from 'uuid';
-const console = Logger("[Smart Agent Router]");
+const console = Logger('[Smart Agent Router]');
export interface RouterDependencies {
// Debugger dependencies
debugger: {
middlewares: express.RequestHandler[];
- processAgentRequest: (
- agentId: string,
- req: express.Request
- ) => Promise<any>;
+ processAgentRequest: (agentId: string, req: express.Request) => Promise<any>;
getDebugSession: (id: string) => any;
createSseConnection: (req: any) => string;
};
@@ -47,101 +44,90 @@ export interface RouterDependencies {
*/
function shouldUseDebugger(req: any): { useDebugger: boolean; reason: string } {
// 1. Check for explicit agent-runner header (highest priority)
- const forceAgentRunner = req.header("X-FORCE-AGENT-RUNNER") !== undefined;
+ const forceAgentRunner = req.header('X-FORCE-AGENT-RUNNER') !== undefined;
if (forceAgentRunner) {
return {
useDebugger: false,
- reason: "X-FORCE-AGENT-RUNNER header present",
+ reason: 'X-FORCE-AGENT-RUNNER header present',
};
}
// 2. Check for debug headers (second highest priority)
- const debugHeaders = [
- "X-DEBUG-RUN",
- "X-DEBUG-READ",
- "X-DEBUG-INJ",
- "X-DEBUG-STOP",
- "X-DEBUG-SKIP",
- "X-MONITOR-ID",
- ];
+ const debugHeaders = ['X-DEBUG-RUN', 'X-DEBUG-READ', 'X-DEBUG-INJ', 'X-DEBUG-STOP', 'X-DEBUG-SKIP', 'X-MONITOR-ID'];
- const hasDebugHeader = debugHeaders.some(
- (header) => req.header(header) !== undefined
- );
+ const hasDebugHeader = debugHeaders.some(header => req.header(header) !== undefined);
if (hasDebugHeader) {
- return { useDebugger: true, reason: "Debug headers present" };
+ return { useDebugger: true, reason: 'Debug headers present' };
}
// 3. Check for explicit debugger header
- const forceDebugger = req.header("X-FORCE-DEBUGGER") !== undefined;
+ const forceDebugger = req.header('X-FORCE-DEBUGGER') !== undefined;
if (forceDebugger) {
- return { useDebugger: true, reason: "X-FORCE-DEBUGGER header present" };
+ return { useDebugger: true, reason: 'X-FORCE-DEBUGGER header present' };
}
// 4. Default routing based on explicit mode header
- const routingMode = req.header("X-ROUTING-MODE");
- if (routingMode === "debugger") {
- return { useDebugger: true, reason: "X-ROUTING-MODE: debugger" };
+ const routingMode = req.header('X-ROUTING-MODE');
+ if (routingMode === 'debugger') {
+ return { useDebugger: true, reason: 'X-ROUTING-MODE: debugger' };
}
- if (routingMode === "agent-runner") {
- return { useDebugger: false, reason: "X-ROUTING-MODE: agent-runner" };
+ if (routingMode === 'agent-runner') {
+ return { useDebugger: false, reason: 'X-ROUTING-MODE: agent-runner' };
}
// 5. Final fallback: Default to agent-runner for production safety
return {
useDebugger: false,
- reason: "Default production-safe routing (no explicit routing headers)",
+ reason: 'Default production-safe routing (no explicit routing headers)',
};
}
/**
* Creates a smart router that automatically chooses between debugger and agent-runner
*/
-export function createSmartAgentRouter(
- dependencies: RouterDependencies
-): express.Router {
+export function createSmartAgentRouter(dependencies: RouterDependencies): express.Router {
const router = express.Router();
// Add correlation ID for request tracing
router.use((req: any, res, next) => {
- if (!req.headers["x-correlation-id"]) {
- req.headers["x-correlation-id"] = uuidv4();
+ if (!req.headers['x-correlation-id']) {
+ req.headers['x-correlation-id'] = uuidv4();
}
- res.setHeader("x-correlation-id", req.headers["x-correlation-id"]);
+ res.setHeader('x-correlation-id', req.headers['x-correlation-id']);
next();
});
// Debugger-specific routes (always use debugger)
- router.get("/agent/:id/debugSession", async (req, res) => {
+ router.get('/agent/:id/debugSession', async (req, res) => {
try {
const dbgSession = dependencies.debugger.getDebugSession(req.params.id);
res.send({ dbgSession });
} catch (error) {
- console.error("Debug session error:", error);
- res.status(500).json({ error: "Debug session unavailable" });
+ console.error('Debug session error:', error);
+ res.status(500).json({ error: 'Debug session unavailable' });
}
});
- router.get("/agent/:id/monitor", async (req, res) => {
+ router.get('/agent/:id/monitor', async (req, res) => {
try {
const sseId = dependencies.debugger.createSseConnection(req);
- res.setHeader("Content-Type", "text/event-stream");
- res.setHeader("Cache-Control", "no-cache");
- res.setHeader("Connection", "keep-alive");
+ res.setHeader('Content-Type', 'text/event-stream');
+ res.setHeader('Cache-Control', 'no-cache');
+ res.setHeader('Connection', 'keep-alive');
res.write(`event: init\n`);
res.write(`data: ${sseId}\n\n`);
} catch (error) {
- console.error("Monitor error:", error);
- res.status(500).json({ error: "Monitor unavailable" });
+ console.error('Monitor error:', error);
+ res.status(500).json({ error: 'Monitor unavailable' });
}
});
// Smart middleware that chooses the right service
const smartMiddleware = async (req: any, res: express.Response) => {
- const correlationId = req.headers["x-correlation-id"];
+ const correlationId = req.headers['x-correlation-id'];
const startTime = Date.now();
try {
@@ -149,52 +135,34 @@ export function createSmartAgentRouter(
const { useDebugger, reason } = shouldUseDebugger(req);
// Step 2: Apply service-specific middleware (including upload handlers)
- const serviceMiddlewares = useDebugger
- ? dependencies.debugger.middlewares
- : dependencies.agentRunner.middlewares;
-
- console.debug(
- `Applying ${serviceMiddlewares.length} ${
- useDebugger ? "debugger" : "agent-runner"
- } middleware(s)`,
- {
- correlationId,
- middlewares: serviceMiddlewares.map((mw) => mw.name || "anonymous"),
- }
- );
+ const serviceMiddlewares = useDebugger ? dependencies.debugger.middlewares : dependencies.agentRunner.middlewares;
+
+ console.debug(`Applying ${serviceMiddlewares.length} ${useDebugger ? 'debugger' : 'agent-runner'} middleware(s)`, {
+ correlationId,
+ middlewares: serviceMiddlewares.map(mw => mw.name || 'anonymous'),
+ });
await runMiddlewares(req, res, serviceMiddlewares);
- console.log(
- `Routing decision: ${
- useDebugger ? "DEBUGGER" : "AGENT-RUNNER"
- } - ${reason}`,
- {
- correlationId,
- agentId: req._agent?.id,
- path: req.path,
- }
- );
+ console.log(`Routing decision: ${useDebugger ? 'DEBUGGER' : 'AGENT-RUNNER'} - ${reason}`, {
+ correlationId,
+ agentId: req._agent?.id,
+ path: req.path,
+ });
// Step 3: Process with appropriate service
let result: any;
if (useDebugger) {
- result = await dependencies.debugger.processAgentRequest(
- req._agent.id,
- req
- );
+ result = await dependencies.debugger.processAgentRequest(req._agent.id, req);
} else {
- result = await dependencies.agentRunner.processAgentRequest(
- req._agent,
- req
- );
+ result = await dependencies.agentRunner.processAgentRequest(req._agent, req);
}
// Step 4: Send response
const processingTime = Date.now() - startTime;
console.debug(`Request completed`, {
correlationId,
- service: useDebugger ? "debugger" : "agent-runner",
+ service: useDebugger ? 'debugger' : 'agent-runner',
status: result?.status || 200,
processingTime,
});
@@ -209,7 +177,7 @@ export function createSmartAgentRouter(
});
return res.status(500).json({
- error: "Internal Server Error",
+ error: 'Internal Server Error',
correlationId,
timestamp: new Date().toISOString(),
});
@@ -218,11 +186,11 @@ export function createSmartAgentRouter(
// Common API routes
const apiRoutes = [
- { method: "post", path: "/api/*" },
- { method: "get", path: "/api/*" },
- { method: "post", path: "/:version/api/*" },
- { method: "get", path: "/:version/api/*" },
- { method: "post", path: /^\/v[0-9]+(\.[0-9]+)?\/api\/(.+)/ },
+ { method: 'post', path: '/api/*' },
+ { method: 'get', path: '/api/*' },
+ { method: 'post', path: '/:version/api/*' },
+ { method: 'get', path: '/:version/api/*' },
+ { method: 'post', path: /^\/v[0-9]+(\.[0-9]+)?\/api\/(.+)/ },
];
apiRoutes.forEach(({ method, path }) => {
@@ -235,13 +203,9 @@ export function createSmartAgentRouter(
/**
* Helper function to promisify Express middleware
*/
-function runMiddleware(
- req: any,
- res: express.Response,
- middleware: express.RequestHandler
-): Promise<void> {
+function runMiddleware(req: any, res: express.Response, middleware: express.RequestHandler): Promise<void> {
return new Promise((resolve, reject) => {
- middleware(req, res, (err) => {
+ middleware(req, res, err => {
if (err) reject(err);
else resolve();
});
@@ -251,11 +215,7 @@ function runMiddleware(
/**
* Helper function to run an array of middlewares sequentially
*/
-async function runMiddlewares(
- req: any,
- res: express.Response,
- middlewares: express.RequestHandler[]
-): Promise<void> {
+async function runMiddlewares(req: any, res: express.Response, middlewares: express.RequestHandler[]): Promise<void> {
for (const middleware of middlewares) {
await runMiddleware(req, res, middleware);
}
@@ -267,21 +227,18 @@ async function runMiddlewares(
export interface SmartRouterConfig {
enableDebuggerRoutes?: boolean;
enableMetrics?: boolean;
- logLevel?: "debug" | "info" | "warn" | "error";
+ logLevel?: 'debug' | 'info' | 'warn' | 'error';
}
-export function createConfiguredSmartRouter(
- dependencies: RouterDependencies,
- config: SmartRouterConfig = {}
-): express.Router {
+export function createConfiguredSmartRouter(dependencies: RouterDependencies, config: SmartRouterConfig = {}): express.Router {
const router = createSmartAgentRouter(dependencies);
// Add health check endpoint
- router.get("/health/smart-router", (req, res) => {
+ router.get('/health/smart-router', (req, res) => {
res.json({
- status: "healthy",
+ status: 'healthy',
timestamp: new Date().toISOString(),
- version: "1.0.0",
+ version: '1.0.0',
});
});
@@ -294,11 +251,11 @@ export function createConfiguredSmartRouter(
router.use((req: any, res, next) => {
requestCount++;
- res.on("finish", () => {
+ res.on('finish', () => {
// This is a simple way to track which service was used
// In a real implementation, you'd want more sophisticated metrics
- const userAgent = req.headers["user-agent"] || "";
- if (userAgent.includes("debug")) {
+ const userAgent = req.headers['user-agent'] || '';
+ if (userAgent.includes('debug')) {
debuggerCount++;
} else {
agentRunnerCount++;
@@ -308,7 +265,7 @@ export function createConfiguredSmartRouter(
next();
});
- router.get("/metrics/smart-router", (req, res) => {
+ router.get('/metrics/smart-router', (req, res) => {
res.json({
totalRequests: requestCount,
debuggerRequests: debuggerCount,
@@ -341,22 +298,22 @@ export function testRoutingDecision(headers: Record<string, string> = {}): {
*/
export const RoutingHeaders = {
// Force agent-runner (highest priority)
- FORCE_AGENT_RUNNER: { "X-FORCE-AGENT-RUNNER": "true" },
+ FORCE_AGENT_RUNNER: { 'X-FORCE-AGENT-RUNNER': 'true' },
// Force debugger
- FORCE_DEBUGGER: { "X-FORCE-DEBUGGER": "true" },
+ FORCE_DEBUGGER: { 'X-FORCE-DEBUGGER': 'true' },
// Debug session headers
- DEBUG_RUN: { "X-DEBUG-RUN": "true" },
- DEBUG_STOP: { "X-DEBUG-STOP": "true" },
- DEBUG_READ: { "X-DEBUG-READ": "true" },
- DEBUG_INJ: { "X-DEBUG-INJ": "true" },
- DEBUG_SKIP: { "X-DEBUG-SKIP": "true" },
- MONITOR: { "X-MONITOR-ID": "test-monitor" },
+ DEBUG_RUN: { 'X-DEBUG-RUN': 'true' },
+ DEBUG_STOP: { 'X-DEBUG-STOP': 'true' },
+ DEBUG_READ: { 'X-DEBUG-READ': 'true' },
+ DEBUG_INJ: { 'X-DEBUG-INJ': 'true' },
+ DEBUG_SKIP: { 'X-DEBUG-SKIP': 'true' },
+ MONITOR: { 'X-MONITOR-ID': 'test-monitor' },
// Explicit routing mode
- MODE_DEBUGGER: { "X-ROUTING-MODE": "debugger" },
- MODE_AGENT_RUNNER: { "X-ROUTING-MODE": "agent-runner" },
+ MODE_DEBUGGER: { 'X-ROUTING-MODE': 'debugger' },
+ MODE_AGENT_RUNNER: { 'X-ROUTING-MODE': 'agent-runner' },
// No headers (default behavior)
NONE: {},
diff --git a/packages/runtime/src/core/types/declarations/smythos.express.d.ts b/packages/runtime/src/core/types/declarations/smythos.express.d.ts
index 43809955..50810c71 100644
--- a/packages/runtime/src/core/types/declarations/smythos.express.d.ts
+++ b/packages/runtime/src/core/types/declarations/smythos.express.d.ts
@@ -1,8 +1,8 @@
-import multer from "multer";
+import multer from 'multer';
-import { Agent } from "@smythos/sre";
+import { Agent } from '@smythos/sre';
-import Chatbot from "@embodiment/services/Chatbot.class";
+import Chatbot from '@embodiment/services/Chatbot.class';
declare global {
namespace Express {
diff --git a/packages/runtime/src/core/types/llm.types.ts b/packages/runtime/src/core/types/llm.types.ts
index 0aa826bc..161d525c 100644
--- a/packages/runtime/src/core/types/llm.types.ts
+++ b/packages/runtime/src/core/types/llm.types.ts
@@ -1,12 +1,12 @@
export type OpenAiParamsProps = Record<
- string,
- {
- type: string;
- description?: string;
- items?: object;
- additionalProperties?: object;
- enum?: string[];
- }
+ string,
+ {
+ type: string;
+ description?: string;
+ items?: object;
+ additionalProperties?: object;
+ enum?: string[];
+ }
>;
export type OpenAiParams = {
type: string;
@@ -17,4 +17,4 @@ export interface OpenAiFunctionArg {
name: string;
description: string;
parameters: OpenAiParams;
-}
\ No newline at end of file
+}
diff --git a/packages/runtime/src/core/types/openapi.types.ts b/packages/runtime/src/core/types/openapi.types.ts
index 2f107a62..7bcb7b10 100644
--- a/packages/runtime/src/core/types/openapi.types.ts
+++ b/packages/runtime/src/core/types/openapi.types.ts
@@ -4,53 +4,53 @@
*/
export interface AgentData {
- id?: string;
- name?: string;
- data?: {
- version?: string;
- behavior?: string;
- shortDescription?: string;
- description?: string;
- components?: Array<AgentComponent>;
- };
- settings?: { [key: string]: any };
- embodiments?: any[];
- deployed?: boolean;
+ id?: string;
+ name?: string;
+ data?: {
+ version?: string;
+ behavior?: string;
+ shortDescription?: string;
+ description?: string;
+ components?: Array<AgentComponent>;
+ };
+ settings?: { [key: string]: any };
+ embodiments?: any[];
+ deployed?: boolean;
}
export interface AgentComponent {
- name: string;
- data: {
- endpoint?: string;
- method?: string;
- description?: string;
- doc?: string;
- ai_exposed?: boolean;
- };
- inputs?: Array<AgentInput>;
+ name: string;
+ data: {
+ endpoint?: string;
+ method?: string;
+ description?: string;
+ doc?: string;
+ ai_exposed?: boolean;
+ };
+ inputs?: Array<AgentInput>;
}
export interface AgentInput {
- name: string;
- type: string;
- description?: string;
- optional?: boolean;
- defaultVal?: any;
+ name: string;
+ type: string;
+ description?: string;
+ optional?: boolean;
+ defaultVal?: any;
}
export interface OpenAPISpec {
- openapi: string;
- info: {
- title: string;
- description: string;
- version: string;
- };
- servers: Array<{ url: string }>;
- paths: { [path: string]: any };
- components?: {
- schemas?: { [key: string]: any };
- securitySchemes?: { [key: string]: any };
- };
- security?: Array<{ [key: string]: string[] }>;
- [key: string]: any; // Allow additional OpenAPI properties
+ openapi: string;
+ info: {
+ title: string;
+ description: string;
+ version: string;
+ };
+ servers: Array<{ url: string }>;
+ paths: { [path: string]: any };
+ components?: {
+ schemas?: { [key: string]: any };
+ securitySchemes?: { [key: string]: any };
+ };
+ security?: Array<{ [key: string]: string[] }>;
+ [key: string]: any; // Allow additional OpenAPI properties
}
diff --git a/packages/runtime/src/core/utils/apiError.ts b/packages/runtime/src/core/utils/apiError.ts
index 95b231ee..6779e08a 100644
--- a/packages/runtime/src/core/utils/apiError.ts
+++ b/packages/runtime/src/core/utils/apiError.ts
@@ -8,33 +8,33 @@
*/
class ApiError extends Error {
- statusCode: number | null | undefined;
+ statusCode: number | null | undefined;
- isOperational: boolean;
+ isOperational: boolean;
- stack: string | undefined;
+ stack: string | undefined;
- errKey: string | undefined;
+ errKey: string | undefined;
- isApiError: boolean;
+ 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
- */
+ /**
+ *
+ * @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;
- }
+ // 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/runtime/src/core/utils/chat.utils.ts b/packages/runtime/src/core/utils/chat.utils.ts
index 4430f81b..8580259c 100644
--- a/packages/runtime/src/core/utils/chat.utils.ts
+++ b/packages/runtime/src/core/utils/chat.utils.ts
@@ -2,32 +2,32 @@ import crypto from 'crypto';
import { getCurrentFormattedDate, toDateFromFormattedDateStr } from './date-time.utils';
export type ChatConversationsEnv = 'test' | 'prod';
export const CHAT_PREFIXES: Record<ChatConversationsEnv, string> = {
- test: 'chat-test-',
- prod: 'chat-',
+ test: 'chat-test-',
+ prod: 'chat-',
};
export const buildConversationId = (uid?: string, isTestConv = false) => {
- const prefix = isTestConv ? CHAT_PREFIXES.test : CHAT_PREFIXES.prod;
- const convId = uid ?? `${prefix}${getCurrentFormattedDate()}-${crypto.randomBytes(8).toString('hex')}`;
- return `${prefix}${getCurrentFormattedDate()}-${convId}`;
+ const prefix = isTestConv ? CHAT_PREFIXES.test : CHAT_PREFIXES.prod;
+ const convId = uid ?? `${prefix}${getCurrentFormattedDate()}-${crypto.randomBytes(8).toString('hex')}`;
+ return `${prefix}${getCurrentFormattedDate()}-${convId}`;
};
export const parseDateFromConvId = (convId: string) => {
- const match = convId.match(/\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}/);
+ const match = convId.match(/\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}/);
- if (!match) return null;
- return toDateFromFormattedDateStr(match[0]);
+ if (!match) return null;
+ return toDateFromFormattedDateStr(match[0]);
};
export const getChatPrefixByEnv = (env: ChatConversationsEnv) => {
- return CHAT_PREFIXES[env];
+ return CHAT_PREFIXES[env];
};
export const parseDateRange = (dateRange: string) => {
- const [start, end] = dateRange.split(',');
- return { start: parseInt(start), end: parseInt(end) };
+ const [start, end] = dateRange.split(',');
+ return { start: parseInt(start), end: parseInt(end) };
};
export const isValidDateRange = (dateRange: string) => {
- if (!dateRange) return false;
- const { start, end } = parseDateRange(dateRange);
- return !isNaN(start) && !isNaN(end) && start < end;
+ if (!dateRange) return false;
+ const { start, end } = parseDateRange(dateRange);
+ return !isNaN(start) && !isNaN(end) && start < end;
};
diff --git a/packages/runtime/src/core/utils/date-time.utils.ts b/packages/runtime/src/core/utils/date-time.utils.ts
index 9184e5d5..d53904a6 100644
--- a/packages/runtime/src/core/utils/date-time.utils.ts
+++ b/packages/runtime/src/core/utils/date-time.utils.ts
@@ -1,27 +1,27 @@
export function getCurrentFormattedDate() {
- const date = new Date();
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
- const day = String(date.getDate()).padStart(2, '0');
- const hours = String(date.getHours()).padStart(2, '0');
- const minutes = String(date.getMinutes()).padStart(2, '0');
- const seconds = String(date.getSeconds()).padStart(2, '0');
- return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
+ const date = new Date();
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
+ const day = String(date.getDate()).padStart(2, '0');
+ const hours = String(date.getHours()).padStart(2, '0');
+ const minutes = String(date.getMinutes()).padStart(2, '0');
+ const seconds = String(date.getSeconds()).padStart(2, '0');
+ return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
}
export function toDateFromFormattedDateStr(formattedDate: string) {
- const [year, month, day, hour, minute, second] = formattedDate.split('-').map(Number);
- return new Date(year, month - 1, day, hour, minute, second);
+ const [year, month, day, hour, minute, second] = formattedDate.split('-').map(Number);
+ return new Date(year, month - 1, day, hour, minute, second);
}
export function getDayFormattedDate() {
- const date = new Date();
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
- const day = String(date.getDate()).padStart(2, '0');
- return `${year}-${month}-${day}`;
+ const date = new Date();
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
+ const day = String(date.getDate()).padStart(2, '0');
+ return `${year}-${month}-${day}`;
}
export function delay(ms) {
- return new Promise((r) => setTimeout(r, ms));
+ return new Promise(r => setTimeout(r, ms));
}
diff --git a/packages/runtime/src/core/utils/general.utils.ts b/packages/runtime/src/core/utils/general.utils.ts
index 75de713d..d12e03dc 100644
--- a/packages/runtime/src/core/utils/general.utils.ts
+++ b/packages/runtime/src/core/utils/general.utils.ts
@@ -1,52 +1,52 @@
import fs from 'fs/promises';
export function uid() {
- return (Date.now() + Math.random()).toString(36).replace('.', '').toUpperCase();
+ return (Date.now() + Math.random()).toString(36).replace('.', '').toUpperCase();
}
export const hasKeyTemplateVar = (str: string = ''): boolean => {
- if (!str || typeof str !== 'string') return false;
- return (str?.match(/{{KEY\((.*?)\)}}/g) ?? []).length > 0;
+ if (!str || typeof str !== 'string') return false;
+ return (str?.match(/{{KEY\((.*?)\)}}/g) ?? []).length > 0;
};
export function parseTemplate(str, obj, { escapeString = true, processUnmatched = true, unmached = '' } = {}) {
- try {
- const parsed = str?.replace(/{{(.*?)}}/g, function (match, varName) {
- // if key template var, return as is
- if (hasKeyTemplateVar(match)) return match;
-
- let objVal = obj[varName.trim()];
-
- if (typeof objVal === 'object') {
- objVal = JSON.stringify(objVal);
- } else {
- if (escapeString && typeof objVal === 'string') {
- //escape double quotes, slashes ...
- objVal = objVal?.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t');
- }
- }
-
- // Need to consider boolean 'false' as a valid value
- // const val = objVal || match;
- const val = objVal !== undefined ? objVal : match;
-
- return typeof val == 'string' || typeof val == 'number' ? val : JSON.stringify(val);
- });
-
- //replace unmached vars with default value, make sure to ignore the key template var
- return str == parsed && processUnmatched ? parsed?.replace(/{{(?!KEY\().*?}}/g, unmached) : parsed;
- } catch (err) {
- console.log('Error on parse template: ', err);
-
- return str;
- }
+ try {
+ const parsed = str?.replace(/{{(.*?)}}/g, function (match, varName) {
+ // if key template var, return as is
+ if (hasKeyTemplateVar(match)) return match;
+
+ let objVal = obj[varName.trim()];
+
+ if (typeof objVal === 'object') {
+ objVal = JSON.stringify(objVal);
+ } else {
+ if (escapeString && typeof objVal === 'string') {
+ //escape double quotes, slashes ...
+ objVal = objVal?.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t');
+ }
+ }
+
+ // Need to consider boolean 'false' as a valid value
+ // const val = objVal || match;
+ const val = objVal !== undefined ? objVal : match;
+
+ return typeof val == 'string' || typeof val == 'number' ? val : JSON.stringify(val);
+ });
+
+ //replace unmached vars with default value, make sure to ignore the key template var
+ return str == parsed && processUnmatched ? parsed?.replace(/{{(?!KEY\().*?}}/g, unmached) : parsed;
+ } catch (err) {
+ console.log('Error on parse template: ', err);
+
+ return str;
+ }
}
export const fsExists = async (path: string) => {
- try {
- await fs.access(path);
- return true;
- } catch {
- return false;
- }
+ try {
+ await fs.access(path);
+ return true;
+ } catch {
+ return false;
+ }
};
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index 6ed2d938..8103cade 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -1,35 +1,32 @@
-import { Logger, SmythRuntime, version } from "@smythos/sre";
-import compression from "compression";
-import cookieParser from "cookie-parser";
-import crypto from "crypto";
-import express from "express";
-import session from "express-session";
-import { Server } from "http";
-import path from "path";
-import url from "url";
+import { Logger, SmythRuntime, version } from '@smythos/sre';
+import compression from 'compression';
+import cookieParser from 'cookie-parser';
+import crypto from 'crypto';
+import express from 'express';
+import session from 'express-session';
+import { Server } from 'http';
+import path from 'path';
+import url from 'url';
// Core imports
-import config from "@core/config";
-import { modelsConfig } from "@core/config/models.config";
-import { startServers } from "@core/management-router";
-import cors from "@core/middlewares/cors.mw";
-import { errorHandler, notFoundHandler } from "@core/middlewares/error.mw";
-import RateLimiter from "@core/middlewares/rateLimiter.mw";
-import { uploadHandler } from "@core/middlewares/uploadHandler.mw";
-import { requestContext } from "@core/services/request-context";
+import config from '@core/config';
+import { modelsConfig } from '@core/config/models.config';
+import { startServers } from '@core/management-router';
+import cors from '@core/middlewares/cors.mw';
+import { errorHandler, notFoundHandler } from '@core/middlewares/error.mw';
+import RateLimiter from '@core/middlewares/rateLimiter.mw';
+import { uploadHandler } from '@core/middlewares/uploadHandler.mw';
+import { requestContext } from '@core/services/request-context';
-import { registerConnectors } from "@core/connectors/connectorRegistry";
+import { registerConnectors } from '@core/connectors/connectorRegistry';
// Routes are handled by configureAgentRouters
// Shared router configuration
-import {
- configureAgentRouters,
- createCombinedServerConfig,
-} from "@core/router-config";
+import { configureAgentRouters, createCombinedServerConfig } from '@core/router-config';
// Embodiment imports
-import { routes as embodimentRoutes } from "@embodiment/routes";
+import { routes as embodimentRoutes } from '@embodiment/routes';
const app = express();
const port = config.env.PORT;
@@ -39,51 +36,51 @@ registerConnectors();
const sre = SmythRuntime.Instance.init({
Cache: {
- Connector: "RAM",
+ Connector: 'RAM',
Settings: {},
},
Account: {
- Connector: "SmythOSSAccount",
+ Connector: 'SmythOSSAccount',
Settings: {
oAuthAppID: config.env.LOGTO_M2M_APP_ID,
oAuthAppSecret: config.env.LOGTO_M2M_APP_SECRET,
oAuthBaseUrl: `${config.env.LOGTO_SERVER}/oidc/token`,
oAuthResource: config.env.LOGTO_API_RESOURCE,
- oAuthScope: "",
- smythAPIBaseUrl: config.env.MIDDLEWARE_API_BASE_URL + "/_sysapi",
+ oAuthScope: '',
+ smythAPIBaseUrl: config.env.MIDDLEWARE_API_BASE_URL + '/_sysapi',
},
},
Vault: {
- Connector: "JSONFileVault",
+ Connector: 'JSONFileVault',
Settings: {
- file: "./data/vault.json",
- shared: "development",
+ file: './data/vault.json',
+ shared: 'development',
},
},
Component: {
- Connector: "LocalComponent",
+ Connector: 'LocalComponent',
},
ModelsProvider: {
- Connector: "SmythModelsProvider",
+ Connector: 'SmythModelsProvider',
Settings: {
models: modelsConfig,
},
},
AgentData: {
- Connector: "SmythOSSAgentData",
+ Connector: 'SmythOSSAgentData',
Settings: {
- agentStageDomain: config.env.DEFAULT_AGENT_DOMAIN || "",
- agentProdDomain: config.env.PROD_AGENT_DOMAIN || "",
+ agentStageDomain: config.env.DEFAULT_AGENT_DOMAIN || '',
+ agentProdDomain: config.env.PROD_AGENT_DOMAIN || '',
oAuthAppID: config.env.LOGTO_M2M_APP_ID,
oAuthAppSecret: config.env.LOGTO_M2M_APP_SECRET,
oAuthBaseUrl: `${config.env.LOGTO_SERVER}/oidc/token`,
oAuthResource: config.env.LOGTO_API_RESOURCE,
- oAuthScope: "",
- smythAPIBaseUrl: config.env.MIDDLEWARE_API_BASE_URL + "/_sysapi",
+ oAuthScope: '',
+ smythAPIBaseUrl: config.env.MIDDLEWARE_API_BASE_URL + '/_sysapi',
},
},
Log: {
- Connector: "ConsoleLog",
+ Connector: 'ConsoleLog',
Settings: {},
},
});
@@ -91,26 +88,22 @@ const sre = SmythRuntime.Instance.init({
const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
-const console = Logger("runtime-server");
+const console = Logger('runtime-server');
// Helper function for session ID generation
function getCurrentFormattedDate() {
const now = new Date();
- return now.toISOString().slice(0, 10).replace(/-/g, "");
+ return now.toISOString().slice(0, 10).replace(/-/g, '');
}
-app.disable("x-powered-by");
-app.set("trust proxy", 1);
+app.disable('x-powered-by');
+app.set('trust proxy', 1);
app.use(cors);
-app.options("*", cors);
+app.options('*', cors);
// Serve static files first for optimal performance
-app.use(
- "/static",
- [compression()],
- express.static(path.join(__dirname, "../static"))
-);
+app.use('/static', [compression()], express.static(path.join(__dirname, '../static')));
// Request context middleware
app.use((req, res, next) => {
@@ -124,62 +117,59 @@ app.use(cookieParser());
// Session middleware for chatbot functionality
app.use(
session({
- name: "smythos_runtime_session",
- secret: config.env.SESSION_SECRET || "default-session-secret-for-dev",
+ name: 'smythos_runtime_session',
+ secret: config.env.SESSION_SECRET || 'default-session-secret-for-dev',
cookie: {
maxAge: 1 * 24 * 60 * 60 * 1000, // 1 day
- sameSite: config.env.NODE_ENV === "development" ? "lax" : "none",
- secure: config.env.NODE_ENV !== "development",
+ sameSite: config.env.NODE_ENV === 'development' ? 'lax' : 'none',
+ secure: config.env.NODE_ENV !== 'development',
},
resave: false,
saveUninitialized: true,
- genid: (req) => {
+ genid: req => {
if (req.sessionID && req.session) {
return req.sessionID;
}
const domain = req.hostname;
- const isTestDomain = domain.includes(
- `.${config.env.DEFAULT_AGENT_DOMAIN}`
- );
- const prefix = isTestDomain ? "test-" : "";
+ const isTestDomain = domain.includes(`.${config.env.DEFAULT_AGENT_DOMAIN}`);
+ const prefix = isTestDomain ? 'test-' : '';
const formattedDate = getCurrentFormattedDate();
- const randomString = crypto.randomBytes(8).toString("hex");
+ const randomString = crypto.randomBytes(8).toString('hex');
return `${prefix}${formattedDate}-${randomString}`;
},
- })
+ }),
);
app.use(uploadHandler);
app.use(RateLimiter);
-app.use(express.json({ limit: "10mb" }));
-app.use(express.urlencoded({ extended: false, limit: "100kb" }));
+app.use(express.json({ limit: '10mb' }));
+app.use(express.urlencoded({ extended: false, limit: '100kb' }));
// Health endpoint
-app.get("/health", (req: any, res) => {
+app.get('/health', (req: any, res) => {
let agent_domain = config.env.DEFAULT_AGENT_DOMAIN;
- if (config.env.AGENT_DOMAIN_PORT)
- agent_domain += `:${config.env.AGENT_DOMAIN_PORT}`;
+ if (config.env.AGENT_DOMAIN_PORT) agent_domain += `:${config.env.AGENT_DOMAIN_PORT}`;
res.send({
- message: "Health Check Complete",
+ message: 'Health Check Complete',
hostname: req.hostname,
agent_domain,
success: true,
node: port?.toString()?.substr(2),
- name: "smythos-runtime-server",
+ name: 'smythos-runtime-server',
sre_version: version,
});
});
// Root endpoint
-app.get("/", (req: any, res) => {
+app.get('/', (req: any, res) => {
res.send(`SmythOS Runtime Server`);
});
// Configure agent routers using shared implementation
configureAgentRouters(app, createCombinedServerConfig());
-app.use("/", embodimentRoutes);
+app.use('/', embodimentRoutes);
// 404 handler - must come before error handler
app.use(notFoundHandler);
@@ -191,31 +181,27 @@ let server: Server | null = null;
(async () => {
try {
- console.info("🚀 Starting SmythOS Runtime Services...");
- console.info("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
+ console.info('🚀 Starting SmythOS Runtime Services...');
+ console.info('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
// Start the main servers (runtime + management)
- console.info("⚡ Starting Main Runtime Services...");
+ console.info('⚡ Starting Main Runtime Services...');
server = startServers();
// Log all running services
- console.info("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
- console.info("🎯 All Services Running:");
- console.info(
- ` • Management Server: http://localhost:${
- config.env.ADMIN_PORT || "5054"
- }`
- );
+ console.info('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
+ console.info('🎯 All Services Running:');
+ console.info(` • Management Server: http://localhost:${config.env.ADMIN_PORT || '5054'}`);
console.info(` • Runtime Server: http://localhost:${port}`);
- console.info("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
- console.info("✨ SmythOS Runtime is ready!");
+ console.info('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
+ console.info('✨ SmythOS Runtime is ready!');
} catch (error) {
- console.error("❌ Failed to start services:", error);
+ console.error('❌ Failed to start services:', error);
}
})();
-process.on("uncaughtException", (err) => {
- console.error("An uncaught error occurred!");
+process.on('uncaughtException', err => {
+ console.error('An uncaught error occurred!');
console.error(err.stack);
});
@@ -227,19 +213,19 @@ const gracefulShutdown = async (signal: string) => {
// Close HTTP server if it exists
if (server) {
server.close(() => {
- console.info("HTTP server closed");
+ console.info('HTTP server closed');
process.exit(0);
});
} else {
process.exit(0);
}
} catch (error) {
- console.error("Error during shutdown:", error);
+ console.error('Error during shutdown:', error);
process.exit(1);
}
};
-process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));
-process.on("SIGINT", () => gracefulShutdown("SIGINT"));
+process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
+process.on('SIGINT', () => gracefulShutdown('SIGINT'));
export { app };
diff --git a/packages/runtime/src/modules/agent-runner/constants.ts b/packages/runtime/src/modules/agent-runner/constants.ts
index 273f2f99..1844d63e 100644
--- a/packages/runtime/src/modules/agent-runner/constants.ts
+++ b/packages/runtime/src/modules/agent-runner/constants.ts
@@ -1 +1 @@
-export const DEFAULT_FILE_PARSING_ENDPOINT = "/api/process_attachment_fallback";
+export const DEFAULT_FILE_PARSING_ENDPOINT = '/api/process_attachment_fallback';
diff --git a/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/bearer.ts b/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/bearer.ts
index 354cc00f..de802fff 100644
--- a/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/bearer.ts
+++ b/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/bearer.ts
@@ -3,23 +3,23 @@ import axios from 'axios';
import qs from 'qs';
const mwFactory = (config: any) => {
- // Middleware to validate an access token using the token introspection endpoint
- const validateTokenMiddleware = async (req: Request, res: Response, next: NextFunction) => {
- // Extract the token from the request header or URL query
- const token = req.headers['authorization']?.split(' ')[1] || req.query.token;
+ // Middleware to validate an access token using the token introspection endpoint
+ const validateTokenMiddleware = async (req: Request, res: Response, next: NextFunction) => {
+ // Extract the token from the request header or URL query
+ const token = req.headers['authorization']?.split(' ')[1] || req.query.token;
- if (!token) {
- return res.status(401).json({ error: 'Access token is required' });
- }
+ if (!token) {
+ return res.status(401).json({ error: 'Access token is required' });
+ }
- if (token == config.token) {
- next();
- } else {
- // Token is not active
- res.status(401).json({ error: 'Invalid access token' });
- }
- };
- return validateTokenMiddleware;
+ if (token == config.token) {
+ next();
+ } else {
+ // Token is not active
+ res.status(401).json({ error: 'Invalid access token' });
+ }
+ };
+ return validateTokenMiddleware;
};
export default mwFactory;
diff --git a/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/index.ts b/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/index.ts
index 6422c9f8..6d65d401 100644
--- a/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/index.ts
+++ b/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/index.ts
@@ -1,43 +1,41 @@
-import { NextFunction, Response } from "express";
+import { NextFunction, Response } from 'express';
-import { Logger } from "@smythos/sre";
+import { Logger } from '@smythos/sre';
-import { getAgentAuthData } from "@core/helpers/agent.helper";
+import { getAgentAuthData } from '@core/helpers/agent.helper';
-import BearerMWFactory from "./bearer";
-import OIDCMWFactory from "./oidc";
+import BearerMWFactory from './bearer';
+import OIDCMWFactory from './oidc';
-const console = Logger("(Agent Runner) Middleware: Agent OAuth");
+const console = Logger('(Agent Runner) Middleware: Agent OAuth');
//this maps to agent.auth.provider entry, the selected provider is stored in agent.auth.method
const providers = {
- "oauth-oidc": OIDCMWFactory,
- "api-key-bearer": BearerMWFactory,
+ 'oauth-oidc': OIDCMWFactory,
+ 'api-key-bearer': BearerMWFactory,
};
const middleware = async (req: any, res: Response, next: NextFunction) => {
- console.log("Agent Auth Middleware");
+ console.log('Agent Auth Middleware');
const agent: any = req._agent;
if (!agent) {
- return res.status(500).send({ error: "Agent not found" });
+ return res.status(500).send({ error: 'Agent not found' });
}
- if (agent?.auth?.method && agent?.auth?.method != "none") {
- console.log("Using agent-oauth middleware");
+ if (agent?.auth?.method && agent?.auth?.method != 'none') {
+ console.log('Using agent-oauth middleware');
// #region Get auth data from settings
const authFromSettings = await getAgentAuthData(agent.id);
const legacyAuthData = agent?.auth || {};
- const authData = authFromSettings?.provider
- ? authFromSettings
- : legacyAuthData;
+ const authData = authFromSettings?.provider ? authFromSettings : legacyAuthData;
// #endregion
const providerInfo = authData?.provider?.[authData?.method];
if (!providerInfo) {
console.warn(`Auth provider ${agent?.auth?.method} not configured`);
- return res.status(401).send({ error: "Auth provider not configured" });
+ return res.status(401).send({ error: 'Auth provider not configured' });
}
const authProvider = providers[agent?.auth?.method];
diff --git a/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/oidc.ts b/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/oidc.ts
index 16abe8f7..b57779fe 100644
--- a/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/oidc.ts
+++ b/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/oidc.ts
@@ -5,204 +5,204 @@ import jwt from 'jsonwebtoken';
import jwksClient from 'jwks-rsa';
function isJWT(token) {
- const parts = token.split('.');
- if (parts.length === 3) {
- try {
- const header = JSON.parse(Buffer.from(parts[0], 'base64').toString('utf8'));
- const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString('utf8'));
-
- // Optionally, check if header contains typical JWT properties
- if (header.alg && header.typ) {
- return true;
- }
- } catch (error) {
- // Errors in parsing mean this isn't a valid JWT
- return false;
- }
+ const parts = token.split('.');
+ if (parts.length === 3) {
+ try {
+ const header = JSON.parse(Buffer.from(parts[0], 'base64').toString('utf8'));
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString('utf8'));
+
+ // Optionally, check if header contains typical JWT properties
+ if (header.alg && header.typ) {
+ return true;
+ }
+ } catch (error) {
+ // Errors in parsing mean this isn't a valid JWT
+ return false;
}
- return false; // Not in JWT format if it doesn't have three parts
+ }
+ return false; // Not in JWT format if it doesn't have three parts
}
//FIXME : handle JWT tokens as well
const mwFactory = async (providerInfo: any, res: Response) => {
- console.log('Agent Auth OIDC');
- const authOIDCConfigURL = providerInfo.OIDCConfigURL;
- const clientID = providerInfo.clientID;
- const clientSecret = providerInfo.clientSecret;
- const allowedEmails = (providerInfo.allowedEmails || []).filter((e: string) => e.trim());
-
- if (!authOIDCConfigURL || !clientID || !clientSecret) {
- console.log('OIDC:Auth provider not configured');
- return res.status(401).send({ error: 'Auth provider not configured' });
- }
-
- const openid: any = await axios.get(authOIDCConfigURL).catch((error) => ({ error }));
-
- if (openid?.error) {
- console.log('OIDC:Error getting OIDC config');
- return res.status(401).send({ error: 'Error getting OIDC config' });
- }
-
- const config = { openid: openid.data, clientID, clientSecret };
+ console.log('Agent Auth OIDC');
+ const authOIDCConfigURL = providerInfo.OIDCConfigURL;
+ const clientID = providerInfo.clientID;
+ const clientSecret = providerInfo.clientSecret;
+ const allowedEmails = (providerInfo.allowedEmails || []).filter((e: string) => e.trim());
+
+ if (!authOIDCConfigURL || !clientID || !clientSecret) {
+ console.log('OIDC:Auth provider not configured');
+ return res.status(401).send({ error: 'Auth provider not configured' });
+ }
+
+ const openid: any = await axios.get(authOIDCConfigURL).catch(error => ({ error }));
+
+ if (openid?.error) {
+ console.log('OIDC:Error getting OIDC config');
+ return res.status(401).send({ error: 'Error getting OIDC config' });
+ }
+
+ const config = { openid: openid.data, clientID, clientSecret };
+
+ let jwks;
+ function getKey(header, callback) {
+ jwks.getSigningKey(header.kid, function (err, key: any) {
+ const signingKey = key?.publicKey || key?.rsaPublicKey;
+ callback(null, signingKey);
+ });
+ }
- let jwks;
- function getKey(header, callback) {
- jwks.getSigningKey(header.kid, function (err, key: any) {
- const signingKey = key?.publicKey || key?.rsaPublicKey;
- callback(null, signingKey);
- });
- }
+ // Middleware to validate an opaque access token using the token introspection endpoint
+ const validateOpaqueTokenMiddleware = async (token, req: Request) => {
+ const auth = {
+ username: config.clientID,
+ password: config.clientSecret,
+ };
+ try {
+ // Send a POST request to the introspection endpoint
+ const response = await axios.post(
+ config.openid.introspection_endpoint,
+ qs.stringify({
+ token: token, // The token you want to introspect
+ // Optionally include token_type_hint: 'access_token' if needed
+ }),
+ {
+ // Basic Auth with the client ID and client secret
+ auth,
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ },
+ );
+
+ //console.log('Token introspection response:', config.openid.introspection_endpoint, response.data);
+ // The introspection response will contain a boolean "active" field indicating validity
+ if (response.data && response.data.active) {
+ // Token is valid; you could attach token details to the request object if needed
+ const oidc_introspect_data = response.data; // This attaches the token data to the request object
+ //console.log('OIDC:Token introspection response:', oidc_introspect_data);
- // Middleware to validate an opaque access token using the token introspection endpoint
- const validateOpaqueTokenMiddleware = async (token, req: Request) => {
- const auth = {
- username: config.clientID,
- password: config.clientSecret,
- };
try {
- // Send a POST request to the introspection endpoint
- const response = await axios.post(
- config.openid.introspection_endpoint,
- qs.stringify({
- token: token, // The token you want to introspect
- // Optionally include token_type_hint: 'access_token' if needed
- }),
- {
- // Basic Auth with the client ID and client secret
- auth,
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- },
- );
-
- //console.log('Token introspection response:', config.openid.introspection_endpoint, response.data);
- // The introspection response will contain a boolean "active" field indicating validity
- if (response.data && response.data.active) {
- // Token is valid; you could attach token details to the request object if needed
- const oidc_introspect_data = response.data; // This attaches the token data to the request object
- //console.log('OIDC:Token introspection response:', oidc_introspect_data);
-
- try {
- //TODO : cache this for a short time
- const userInfo = await axios.get(config.openid.userinfo_endpoint, {
- headers: {
- Authorization: `Bearer ${token}`,
- },
- });
-
- //check if the user is allowed
- console.log('OIDC:userinfo', userInfo?.data);
-
- if (allowedEmails.length > 0) {
- const email = userInfo?.data?.email || '';
- const domain = email.split('@')[1];
- if (!allowedEmails.includes(email) && !allowedEmails.includes(domain)) {
- console.log('OIDC:User not allowed', email, domain);
- //the status code should be 403 here, but chatGPT goes in infinite loop if we use it.
- return { error: 'OIDC:User not allowed', status: 200 };
- }
- }
-
- req['_agent_authinfo'] = { userinfo: userInfo?.data };
-
- return { error: null };
- } catch (error) {
- return { error: 'OIDC:userinfo failed', status: 401 };
- }
- } else {
- // Token is not active
- return { error: 'OIDC:Agent Access token is invalid or expired', status: 401 };
+ //TODO : cache this for a short time
+ const userInfo = await axios.get(config.openid.userinfo_endpoint, {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ });
+
+ //check if the user is allowed
+ console.log('OIDC:userinfo', userInfo?.data);
+
+ if (allowedEmails.length > 0) {
+ const email = userInfo?.data?.email || '';
+ const domain = email.split('@')[1];
+ if (!allowedEmails.includes(email) && !allowedEmails.includes(domain)) {
+ console.log('OIDC:User not allowed', email, domain);
+ //the status code should be 403 here, but chatGPT goes in infinite loop if we use it.
+ return { error: 'OIDC:User not allowed', status: 200 };
}
- } catch (error) {
- // Handle errors, such as network issues or the introspection endpoint being down
- console.error('Token introspection error:', error);
- return { error: 'OIDC:Internal server error during token validation', status: 500 };
- }
- };
+ }
- const validateJWTTokenMiddleware = async (token, req: Request) => {
- if (!token) {
- return res.status(401).json({ error: 'Access token is required' });
+ req['_agent_authinfo'] = { userinfo: userInfo?.data };
+
+ return { error: null };
+ } catch (error) {
+ return { error: 'OIDC:userinfo failed', status: 401 };
}
+ } else {
+ // Token is not active
+ return { error: 'OIDC:Agent Access token is invalid or expired', status: 401 };
+ }
+ } catch (error) {
+ // Handle errors, such as network issues or the introspection endpoint being down
+ console.error('Token introspection error:', error);
+ return { error: 'OIDC:Internal server error during token validation', status: 500 };
+ }
+ };
- // Check if token is a JWT
- if (token.split('.').length === 3) {
- // Token is a JWT, validate it
- try {
- const decoded = jwt.verify(token, getKey, {
- algorithms: ['RS256'],
- });
+ const validateJWTTokenMiddleware = async (token, req: Request) => {
+ if (!token) {
+ return res.status(401).json({ error: 'Access token is required' });
+ }
- console.log(decoded);
- return { error: null };
- } catch (err) {
- return res.status(401).json({ error: 'Invalid JWT token' });
- }
- } else if (config.openid.introspection_endpoint) {
- // Token is not a JWT, use introspection endpoint
- try {
- const response = await axios.post(
- config.openid.introspection_endpoint,
- qs.stringify({
- token: token,
- }),
- {
- auth: {
- username: config.clientID,
- password: config.clientSecret,
- },
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- },
- );
+ // Check if token is a JWT
+ if (token.split('.').length === 3) {
+ // Token is a JWT, validate it
+ try {
+ const decoded = jwt.verify(token, getKey, {
+ algorithms: ['RS256'],
+ });
- if (response.data && response.data.active) {
- return { error: null };
- } else {
- return { error: 'Access token is invalid or expired', status: 401 };
- }
- } catch (error) {
- console.error('Token introspection error:', error);
- return { error: 'Internal server error during token validation', status: 500 };
- }
+ console.log(decoded);
+ return { error: null };
+ } catch (err) {
+ return res.status(401).json({ error: 'Invalid JWT token' });
+ }
+ } else if (config.openid.introspection_endpoint) {
+ // Token is not a JWT, use introspection endpoint
+ try {
+ const response = await axios.post(
+ config.openid.introspection_endpoint,
+ qs.stringify({
+ token: token,
+ }),
+ {
+ auth: {
+ username: config.clientID,
+ password: config.clientSecret,
+ },
+ headers: {
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ },
+ );
+
+ if (response.data && response.data.active) {
+ return { error: null };
} else {
- // No suitable method to validate the token
- return { error: 'Unable to validate access token', status: 401 };
+ return { error: 'Access token is invalid or expired', status: 401 };
}
- };
+ } catch (error) {
+ console.error('Token introspection error:', error);
+ return { error: 'Internal server error during token validation', status: 500 };
+ }
+ } else {
+ // No suitable method to validate the token
+ return { error: 'Unable to validate access token', status: 401 };
+ }
+ };
- const validateTokenMiddleware = async (req: Request, res: Response, next: NextFunction) => {
- const token = req.headers['authorization']?.split(' ')[1] || req.query.token;
- if (!token) {
- console.log('OIDC:Access token is required');
- return res.status(401).json({ error: 'Access token is required' });
- }
+ const validateTokenMiddleware = async (req: Request, res: Response, next: NextFunction) => {
+ const token = req.headers['authorization']?.split(' ')[1] || req.query.token;
+ if (!token) {
+ console.log('OIDC:Access token is required');
+ return res.status(401).json({ error: 'Access token is required' });
+ }
- const isJWTToken = isJWT(token);
-
- if (isJWTToken) {
- // Set up JWKS client using the JWKS URI from the OpenID configuration
- jwks = jwksClient({
- jwksUri: config.openid.jwks_uri,
- });
- const result: any = await validateJWTTokenMiddleware(token, req);
- if (result.error) {
- console.log('OIDC:JWT validation failed', result.error);
- return res.status(result.status).json({ error: result.error });
- }
- return next();
- } else {
- const result: any = await validateOpaqueTokenMiddleware(token, req);
- if (result.error) {
- console.log('OIDC:Token validation failed', result.error);
- return res.status(result.status).json({ error: result.error });
- }
- return next();
- }
- };
- return validateTokenMiddleware;
+ const isJWTToken = isJWT(token);
+
+ if (isJWTToken) {
+ // Set up JWKS client using the JWKS URI from the OpenID configuration
+ jwks = jwksClient({
+ jwksUri: config.openid.jwks_uri,
+ });
+ const result: any = await validateJWTTokenMiddleware(token, req);
+ if (result.error) {
+ console.log('OIDC:JWT validation failed', result.error);
+ return res.status(result.status).json({ error: result.error });
+ }
+ return next();
+ } else {
+ const result: any = await validateOpaqueTokenMiddleware(token, req);
+ if (result.error) {
+ console.log('OIDC:Token validation failed', result.error);
+ return res.status(result.status).json({ error: result.error });
+ }
+ return next();
+ }
+ };
+ return validateTokenMiddleware;
};
export default mwFactory;
diff --git a/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts b/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts
index 4331c5c7..e80bb13c 100644
--- a/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts
+++ b/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts
@@ -1,29 +1,24 @@
-import { ConnectorService, Logger } from "@smythos/sre";
+import { ConnectorService, Logger } from '@smythos/sre';
-import config from "@core/config";
-import {
- addDefaultComponentsAndConnections,
- extractAgentVerionsAndPath,
- getAgentDomainById,
-} from "@core/helpers/agent.helper";
+import config from '@core/config';
+import { addDefaultComponentsAndConnections, extractAgentVerionsAndPath, getAgentDomainById } from '@core/helpers/agent.helper';
-import { DEFAULT_FILE_PARSING_ENDPOINT } from "@agent-runner/constants";
+import { DEFAULT_FILE_PARSING_ENDPOINT } from '@agent-runner/constants';
-const console = Logger("(Agent Runner) Middleware: Agent Loader");
+const console = Logger('(Agent Runner) Middleware: Agent Loader');
export default async function agentLoader(req, res, next) {
- console.log("agentLoader", req.path);
+ console.log('agentLoader', req.path);
const agentDataConnector = ConnectorService.getAgentDataConnector();
- if (req.path.startsWith("/static/")) {
+ if (req.path.startsWith('/static/')) {
return next();
}
- let agentId = req.header("X-AGENT-ID");
- let agentVersion = req.header("X-AGENT-VERSION") || "";
- const isAgentChatRequest = req.header("x-conversation-id") !== undefined;
- const isAgentFileParsingRequest =
- isAgentChatRequest || req.header("X-AGENT-REMOTE-CALL") !== undefined;
- let agentDomain: any = "";
+ let agentId = req.header('X-AGENT-ID');
+ let agentVersion = req.header('X-AGENT-VERSION') || '';
+ const isAgentChatRequest = req.header('x-conversation-id') !== undefined;
+ const isAgentFileParsingRequest = isAgentChatRequest || req.header('X-AGENT-REMOTE-CALL') !== undefined;
+ let agentDomain: any = '';
let isTestDomain = false;
let { path, version } = extractAgentVerionsAndPath(req.path);
if (!version) version = agentVersion;
@@ -33,17 +28,15 @@ export default async function agentLoader(req, res, next) {
try {
const result = agentDataConnector?.getAgentIdByDomain?.(domain);
- if (result && typeof result.catch === "function") {
- agentId = await result.catch((error) => {
+ if (result && typeof result.catch === 'function') {
+ agentId = await result.catch(error => {
console.error(error);
});
} else {
- console.error(
- "getAgentIdByDomain method is not available or does not return a promise"
- );
+ console.error('getAgentIdByDomain method is not available or does not return a promise');
}
} catch (error) {
- console.error("Error calling getAgentIdByDomain:", error);
+ console.error('Error calling getAgentIdByDomain:', error);
}
agentDomain = domain;
if (agentId && domain.includes(config.env.DEFAULT_AGENT_DOMAIN)) {
@@ -51,47 +44,40 @@ export default async function agentLoader(req, res, next) {
}
}
if (agentId) {
- if (!isTestDomain && agentId && req.hostname.includes("localhost")) {
- console.log(
- `Agent is running on localhost (${req.hostname}), assuming test domain`
- );
+ if (!isTestDomain && agentId && req.hostname.includes('localhost')) {
+ console.log(`Agent is running on localhost (${req.hostname}), assuming test domain`);
isTestDomain = true;
}
if (agentDomain && !isTestDomain && !version) {
//when using a production domain but no version is specified, use latest
- version = "latest";
+ version = 'latest';
}
let agentData;
try {
const result = agentDataConnector?.getAgentData?.(agentId, version);
- if (result && typeof result.catch === "function") {
- agentData = await result.catch((error) => {
+ if (result && typeof result.catch === 'function') {
+ agentData = await result.catch(error => {
console.error(error);
return { error: error.message };
});
} else {
- console.error(
- "getAgentData method is not available or does not return a promise"
- );
- agentData = { error: "getAgentData method is not available" };
+ console.error('getAgentData method is not available or does not return a promise');
+ agentData = { error: 'getAgentData method is not available' };
}
} catch (error) {
- console.error("Error calling getAgentData:", error);
+ console.error('Error calling getAgentData:', error);
agentData = { error: error.message };
}
if (agentData?.error) {
// return Not found error for storage requests
- if (req.path.startsWith("/storage/")) {
+ if (req.path.startsWith('/storage/')) {
return res.status(404).send(`File Not Found`);
}
return res.status(500).send({ error: agentData.error });
}
- if (
- isAgentFileParsingRequest &&
- path.startsWith(DEFAULT_FILE_PARSING_ENDPOINT)
- ) {
+ if (isAgentFileParsingRequest && path.startsWith(DEFAULT_FILE_PARSING_ENDPOINT)) {
addDefaultComponentsAndConnections(agentData);
}
@@ -103,9 +89,7 @@ export default async function agentLoader(req, res, next) {
req._agent.usingTestDomain = isTestDomain;
req._agent.domain = agentDomain || (await getAgentDomainById(agentId));
- console.log(
- `Loaded Agent:${agentId} v=${version} path=${path} isTestDomain=${isTestDomain} domain=${agentDomain}`
- );
+ console.log(`Loaded Agent:${agentId} v=${version} path=${path} isTestDomain=${isTestDomain} domain=${agentDomain}`);
return next();
}
@@ -116,9 +100,7 @@ export default async function agentLoader(req, res, next) {
function cleanAgentData(agentData) {
if (agentData) {
// remove Note components
- agentData.data.components = agentData.data.components.filter(
- (c) => c.name != "Note"
- );
+ agentData.data.components = agentData.data.components.filter(c => c.name != 'Note');
// remove templateInfo
delete agentData.data?.templateInfo;
diff --git a/packages/runtime/src/modules/agent-runner/middlewares/index.ts b/packages/runtime/src/modules/agent-runner/middlewares/index.ts
index 45f994fa..bf33b21f 100644
--- a/packages/runtime/src/modules/agent-runner/middlewares/index.ts
+++ b/packages/runtime/src/modules/agent-runner/middlewares/index.ts
@@ -1,43 +1,41 @@
-import { NextFunction, Response } from "express";
+import { NextFunction, Response } from 'express';
-import { Logger } from "@smythos/sre";
+import { Logger } from '@smythos/sre';
-import { getAgentAuthData } from "@core/helpers/agent.helper";
+import { getAgentAuthData } from '@core/helpers/agent.helper';
-import BearerMWFactory from "./agent-oauth.mw/bearer";
-import OIDCMWFactory from "./agent-oauth.mw/oidc";
+import BearerMWFactory from './agent-oauth.mw/bearer';
+import OIDCMWFactory from './agent-oauth.mw/oidc';
-const console = Logger("(Agent Runner) Middleware: Index");
+const console = Logger('(Agent Runner) Middleware: Index');
//this maps to agent.auth.provider entry, the selected provider is stored in agent.auth.method
const providers = {
- "oauth-oidc": OIDCMWFactory,
- "api-key-bearer": BearerMWFactory,
+ 'oauth-oidc': OIDCMWFactory,
+ 'api-key-bearer': BearerMWFactory,
};
const middleware = async (req: any, res: Response, next: NextFunction) => {
- console.log("Agent Auth Middleware");
+ console.log('Agent Auth Middleware');
const agent: any = req._agent;
if (!agent) {
- return res.status(500).send({ error: "Agent not found" });
+ return res.status(500).send({ error: 'Agent not found' });
}
- if (agent?.auth?.method && agent?.auth?.method != "none") {
- console.log("Using agent-oauth middleware");
+ if (agent?.auth?.method && agent?.auth?.method != 'none') {
+ console.log('Using agent-oauth middleware');
// #region Get auth data from settings
const authFromSettings = await getAgentAuthData(agent.id);
const legacyAuthData = agent?.auth || {};
- const authData = authFromSettings?.provider
- ? authFromSettings
- : legacyAuthData;
+ const authData = authFromSettings?.provider ? authFromSettings : legacyAuthData;
// #endregion
const providerInfo = authData?.provider?.[authData?.method];
if (!providerInfo) {
console.warn(`Auth provider ${agent?.auth?.method} not configured`);
- return res.status(401).send({ error: "Auth provider not configured" });
+ return res.status(401).send({ error: 'Auth provider not configured' });
}
const authProvider = providers[agent?.auth?.method];
diff --git a/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts b/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts
index 9350eda2..417aead4 100644
--- a/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts
+++ b/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts
@@ -1,20 +1,20 @@
-import axios from "axios";
-import express, { Request, Response } from "express";
-import querystring from "querystring";
+import axios from 'axios';
+import express, { Request, Response } from 'express';
+import querystring from 'querystring';
-import { readAgentOAuthConfig } from "@core/helpers/agent.helper";
+import { readAgentOAuthConfig } from '@core/helpers/agent.helper';
-import agentLoader from "@agent-runner/middlewares/agentLoader.mw";
+import agentLoader from '@agent-runner/middlewares/agentLoader.mw';
const router = express.Router();
router.use(agentLoader);
// @ts-ignore
-router.get("/authorize", async (req: Request, res: Response) => {
+router.get('/authorize', async (req: Request, res: Response) => {
//@ts-ignore
const agent: Agent = req._agent;
if (!agent) {
- return res.status(404).json({ error: "Agent not found" });
+ return res.status(404).json({ error: 'Agent not found' });
}
const authInfo = await readAgentOAuthConfig(agent);
const authorizationURL = authInfo.authorizationURL;
@@ -23,31 +23,31 @@ router.get("/authorize", async (req: Request, res: Response) => {
const client_secret = authInfo.clientSecret;
if (!client_id || !client_secret) {
- return res.status(404).json({ error: "Agent not configured for OAuth" });
+ return res.status(404).json({ error: 'Agent not configured for OAuth' });
}
- console.log("OIDC:AUTHORIZE", req.query);
+ console.log('OIDC:AUTHORIZE', req.query);
const query: any = {
...req.query,
client_id,
- prompt: "consent",
- scope: req.query.scope || "openid offline_access profile email",
+ prompt: 'consent',
+ scope: req.query.scope || 'openid offline_access profile email',
};
- console.log("OIDC:AUTHORIZE PATCHED for OIDC", query);
+ console.log('OIDC:AUTHORIZE PATCHED for OIDC', query);
// Here, we maintain the original query parameters in the redirection
const redirectUrl = new URL(authorizationURL);
redirectUrl.search = new URLSearchParams(query).toString();
- console.log("OIDC:AUTHORIZE redir URL", redirectUrl.href);
+ console.log('OIDC:AUTHORIZE redir URL', redirectUrl.href);
res.redirect(redirectUrl.href);
});
// @ts-ignore
-router.post("/token", async (req: Request, res: Response) => {
+router.post('/token', async (req: Request, res: Response) => {
// @ts-ignore
const agent: Agent = req._agent;
if (!agent) {
- return res.status(404).json({ error: "Agent not found" });
+ return res.status(404).json({ error: 'Agent not found' });
}
const authInfo = await readAgentOAuthConfig(agent);
const authorizationURL = authInfo.authorizationURL;
@@ -56,23 +56,23 @@ router.post("/token", async (req: Request, res: Response) => {
const client_secret = authInfo.clientSecret;
if (!client_id || !client_secret) {
- return res.status(404).json({ error: "Agent not configured for OAuth" });
+ return res.status(404).json({ error: 'Agent not configured for OAuth' });
}
- console.log("OIDC:TOKEN", req.body);
+ console.log('OIDC:TOKEN', req.body);
const data = { ...req.body, client_id, client_secret };
- console.log("OIDC:TOKEN Patched for OIDC", data);
+ console.log('OIDC:TOKEN Patched for OIDC', data);
try {
const result = await axios.post(tokenUrl, querystring.stringify(data), {
headers: {
- "Content-Type": "application/x-www-form-urlencoded",
+ 'Content-Type': 'application/x-www-form-urlencoded',
},
});
- console.log("OIDC:AUTH", result.data);
+ console.log('OIDC:AUTH', result.data);
res.json(result.data);
} catch (error: any) {
if (error?.response?.status === 400) {
- console.log("OIDC:AUTH ERROR status 400", error?.response?.data);
+ console.log('OIDC:AUTH ERROR status 400', error?.response?.data);
return res.status(400).json(error?.response?.data);
// const fakeToken = {
// access_token: '0000401-' + req.body.refresh_token,
@@ -84,8 +84,8 @@ router.post("/token", async (req: Request, res: Response) => {
// };
// return res.status(200).json(fakeToken);
}
- console.log("OIDC:AUTH ERROR 500", error);
- res.status(500).json({ message: "An error occurred" });
+ console.log('OIDC:AUTH ERROR 500', error);
+ res.status(500).json({ message: 'An error occurred' });
}
});
diff --git a/packages/runtime/src/modules/agent-runner/routes/agent/router.ts b/packages/runtime/src/modules/agent-runner/routes/agent/router.ts
index 1741c258..c14a466f 100644
--- a/packages/runtime/src/modules/agent-runner/routes/agent/router.ts
+++ b/packages/runtime/src/modules/agent-runner/routes/agent/router.ts
@@ -1,8 +1,8 @@
-import agentLoader from "@agent-runner/middlewares/agentLoader.mw";
-import { processAgentRequest } from "@agent-runner/services/agent-request-handler";
+import agentLoader from '@agent-runner/middlewares/agentLoader.mw';
+import { processAgentRequest } from '@agent-runner/services/agent-request-handler';
-import { uploadHandler } from "@core/middlewares/uploadHandler.mw";
-import { createAgentRunnerRouter } from "@core/shared-agent-router";
+import { uploadHandler } from '@core/middlewares/uploadHandler.mw';
+import { createAgentRunnerRouter } from '@core/shared-agent-router';
/* agentLoader must come before agentAuth because agentAuth relies on req._agent, set by agentLoader.
Also, uploadHandler should precede agentLoader to parse multipart/form-data correctly */
diff --git a/packages/runtime/src/modules/agent-runner/services/agent-request-handler.ts b/packages/runtime/src/modules/agent-runner/services/agent-request-handler.ts
index 962914c6..9201ffb1 100644
--- a/packages/runtime/src/modules/agent-runner/services/agent-request-handler.ts
+++ b/packages/runtime/src/modules/agent-runner/services/agent-request-handler.ts
@@ -1,30 +1,25 @@
-import { Request } from "express";
+import { Request } from 'express';
-import { AgentProcess, Logger } from "@smythos/sre";
+import { AgentProcess, Logger } from '@smythos/sre';
-const console = Logger("(Agent Runner) Service: Agent Request Handler");
+const console = Logger('(Agent Runner) Service: Agent Request Handler');
export async function processAgentRequest(agent: any, req: Request) {
if (!agent) {
- return { status: 404, data: "Agent not found" };
+ return { status: 404, data: 'Agent not found' };
}
//const req = agent.agentRequest;
- req.socket.on("close", () => {
+ req.socket.on('close', () => {
// console.log('Client socket closed, killing agent');
// Handle the cancellation logic
// agent.kill();
});
- const hasDebugHeader = [
- "X-DEBUG-RUN",
- "X-DEBUG-READ",
- "X-DEBUG-INJ",
- "X-DEBUG-STOP",
- ].some((header) => req.header(header));
+ const hasDebugHeader = ['X-DEBUG-RUN', 'X-DEBUG-READ', 'X-DEBUG-INJ', 'X-DEBUG-STOP'].some(header => req.header(header));
if (hasDebugHeader) {
- return { status: 403, data: "Debug functions are not supported" };
+ return { status: 403, data: 'Debug functions are not supported' };
}
return runAgentProcess(agent, req);
@@ -37,7 +32,7 @@ async function runAgentProcess(agent: any, req: any) {
//deployed agents have a version number
const pathMatches = req.path.match(/(^\/v[0-9]+\.[0-9]+?)?(\/api\/(.+)?)/);
if (!pathMatches || !pathMatches[2]) {
- return { status: 404, data: { error: "Endpoint not found" } };
+ return { status: 404, data: { error: 'Endpoint not found' } };
}
const { data: result } = await AgentProcess.load(req._agent)
@@ -46,10 +41,10 @@ async function runAgentProcess(agent: any, req: any) {
path: req.path,
url: undefined,
})
- .catch((error) => ({ data: { error: error.toString() } }));
+ .catch(error => ({ data: { error: error.toString() } }));
if (result.error) {
- console.error("ERROR", result.error);
+ console.error('ERROR', result.error);
return {
status: 500,
data: {
@@ -69,7 +64,7 @@ async function runAgentProcess(agent: any, req: any) {
return { status: error.response.status, data: error.response.data };
} else {
// Some other error occurred
- return { status: 500, data: "Internal Server Error" };
+ return { status: 500, data: 'Internal Server Error' };
}
}
}
diff --git a/packages/runtime/src/modules/debugger/middlewares/agentLoader.mw.ts b/packages/runtime/src/modules/debugger/middlewares/agentLoader.mw.ts
index 9763dc69..25afae11 100644
--- a/packages/runtime/src/modules/debugger/middlewares/agentLoader.mw.ts
+++ b/packages/runtime/src/modules/debugger/middlewares/agentLoader.mw.ts
@@ -1,33 +1,28 @@
-import { ConnectorService, Logger } from "@smythos/sre";
+import { ConnectorService, Logger } from '@smythos/sre';
-import config from "@core/config";
-import {
- addDefaultComponentsAndConnections,
- extractAgentVerionsAndPath,
- getAgentDomainById,
-} from "@core/helpers/agent.helper";
+import config from '@core/config';
+import { addDefaultComponentsAndConnections, extractAgentVerionsAndPath, getAgentDomainById } from '@core/helpers/agent.helper';
-const console = Logger("[Debugger] Middleware: agentLoader");
+const console = Logger('[Debugger] Middleware: agentLoader');
export default async function agentLoader(req, res, next) {
- console.log("agentLoader", req.path);
+ console.log('agentLoader', req.path);
const agentDataConnector = ConnectorService.getAgentDataConnector();
- if (req.path.startsWith("/static/")) {
+ if (req.path.startsWith('/static/')) {
return next();
}
- let agentId = req.header("X-AGENT-ID");
- let agentVersion = req.header("X-AGENT-VERSION") || "";
- const isAgentChatRequest = req.header("x-conversation-id") !== undefined;
- const isAgentFileParsingRequest =
- isAgentChatRequest || req.header("X-AGENT-REMOTE-CALL") !== undefined;
+ let agentId = req.header('X-AGENT-ID');
+ let agentVersion = req.header('X-AGENT-VERSION') || '';
+ const isAgentChatRequest = req.header('x-conversation-id') !== undefined;
+ const isAgentFileParsingRequest = isAgentChatRequest || req.header('X-AGENT-REMOTE-CALL') !== undefined;
const debugHeader =
- req.header("X-DEBUG-STOP") !== undefined ||
- req.header("X-DEBUG-RUN") !== undefined ||
- req.header("X-DEBUG-INJ") !== undefined ||
- req.header("X-DEBUG-READ") !== undefined;
+ req.header('X-DEBUG-STOP') !== undefined ||
+ req.header('X-DEBUG-RUN') !== undefined ||
+ req.header('X-DEBUG-INJ') !== undefined ||
+ req.header('X-DEBUG-READ') !== undefined;
- let agentDomain: any = "";
+ let agentDomain: any = '';
let isTestDomain = false;
let { path, version } = extractAgentVerionsAndPath(req.path);
if (!version) version = agentVersion;
@@ -37,17 +32,15 @@ export default async function agentLoader(req, res, next) {
if (!agentId) {
try {
const result = agentDataConnector?.getAgentIdByDomain?.(domain);
- if (result && typeof result.catch === "function") {
- agentId = await result.catch((error) => {
+ if (result && typeof result.catch === 'function') {
+ agentId = await result.catch(error => {
console.error(error);
});
} else {
- console.error(
- "getAgentIdByDomain method is not available or does not return a promise"
- );
+ console.error('getAgentIdByDomain method is not available or does not return a promise');
}
} catch (error) {
- console.error("Error calling getAgentIdByDomain:", error);
+ console.error('Error calling getAgentIdByDomain:', error);
}
}
agentDomain = domain;
@@ -55,49 +48,42 @@ export default async function agentLoader(req, res, next) {
isTestDomain = true;
}
if (agentId) {
- if (!isTestDomain && agentId && req.hostname.includes("localhost")) {
- console.log(
- `Host ${req.hostname} is using debug session. Assuming test domain`
- );
+ if (!isTestDomain && agentId && req.hostname.includes('localhost')) {
+ console.log(`Host ${req.hostname} is using debug session. Assuming test domain`);
isTestDomain = true;
}
if (agentDomain && !isTestDomain && !version && !debugHeader) {
//when using a production domain but no version is specified, use latest
- version = "latest";
+ version = 'latest';
}
let agentData;
try {
const result = agentDataConnector?.getAgentData?.(agentId, version);
- if (result && typeof result.catch === "function") {
- agentData = await result.catch((error) => {
+ if (result && typeof result.catch === 'function') {
+ agentData = await result.catch(error => {
console.error(error);
return { error: error.message };
});
} else {
- console.error(
- "getAgentData method is not available or does not return a promise"
- );
- agentData = { error: "getAgentData method is not available" };
+ console.error('getAgentData method is not available or does not return a promise');
+ agentData = { error: 'getAgentData method is not available' };
}
} catch (error) {
- console.error("Error calling getAgentData:", error);
+ console.error('Error calling getAgentData:', error);
agentData = { error: error.message };
}
if (agentData?.error) {
// return Not found error for storage requests
- if (req.path.startsWith("/storage/")) {
+ if (req.path.startsWith('/storage/')) {
return res.status(404).send(`File Not Found`);
}
return res.status(500).send({ error: agentData.error });
}
- if (
- isAgentFileParsingRequest &&
- path.startsWith("/api/process_attachment_fallback")
- ) {
+ if (isAgentFileParsingRequest && path.startsWith('/api/process_attachment_fallback')) {
// only add default components and connections for file parsing agent on file parsing requests
addDefaultComponentsAndConnections(agentData);
- req.headers["x-debug-skip"] = "true"; // should be lowercase
+ req.headers['x-debug-skip'] = 'true'; // should be lowercase
}
// clean up agent data
@@ -106,18 +92,14 @@ export default async function agentLoader(req, res, next) {
req._agent = agentData.data;
if (!isTestDomain && req._agent.debugSessionEnabled && debugHeader) {
- console.log(
- `Host ${req.hostname} is using debug session. Assuming test domain.#2`
- );
+ console.log(`Host ${req.hostname} is using debug session. Assuming test domain.#2`);
isTestDomain = true;
}
req._agent.usingTestDomain = isTestDomain;
req._agent.domain = agentDomain || (await getAgentDomainById(agentId));
- console.log(
- `Loaded Agent:${agentId} v=${version} path=${path} isTestDomain=${isTestDomain} domain=${agentDomain}`
- );
+ console.log(`Loaded Agent:${agentId} v=${version} path=${path} isTestDomain=${isTestDomain} domain=${agentDomain}`);
return next();
}
@@ -127,9 +109,7 @@ export default async function agentLoader(req, res, next) {
function cleanAgentData(agentData) {
if (agentData) {
// remove Note components
- agentData.data.components = agentData.data.components.filter(
- (c) => c.name != "Note"
- );
+ agentData.data.components = agentData.data.components.filter(c => c.name != 'Note');
// remove templateInfo
delete agentData.data?.templateInfo;
diff --git a/packages/runtime/src/modules/debugger/middlewares/teamAccessCheck.mw.ts b/packages/runtime/src/modules/debugger/middlewares/teamAccessCheck.mw.ts
index 431588aa..a8634cdb 100644
--- a/packages/runtime/src/modules/debugger/middlewares/teamAccessCheck.mw.ts
+++ b/packages/runtime/src/modules/debugger/middlewares/teamAccessCheck.mw.ts
@@ -1,41 +1,39 @@
-import { Logger } from "@smythos/sre";
+import { Logger } from '@smythos/sre';
-import { mwUserAPI } from "@core/services/smythAPIReq";
+import { mwUserAPI } from '@core/services/smythAPIReq';
-const console = Logger("(Debugger) Middleware: Team Access Check");
+const console = Logger('(Debugger) Middleware: Team Access Check');
export async function teamAccessCheck(req, res, next) {
let teamId = req.params.teamId;
- const accessToken = req.header("Authorization")
- ? req.header("Authorization").split(" ")[1]
- : null;
+ const accessToken = req.header('Authorization') ? req.header('Authorization').split(' ')[1] : null;
if (!accessToken) {
- return res.status(401).send({ error: "Unauthorized" });
+ return res.status(401).send({ error: 'Unauthorized' });
}
if (!teamId) {
- console.error("Team ID is required");
- return res.status(400).send({ error: "Team ID is required" });
+ console.error('Team ID is required');
+ return res.status(400).send({ error: 'Team ID is required' });
}
try {
const result = await mwUserAPI.get(`/teams/me`, {
headers: {
Authorization: `Bearer ${accessToken}`,
- "x-smyth-team-id": teamId,
+ 'x-smyth-team-id': teamId,
},
});
const team = result?.data?.team || {};
if (teamId !== team?.id) {
- return res.status(401).send({ error: "Unauthorized" });
+ return res.status(401).send({ error: 'Unauthorized' });
}
next();
} catch (err) {
console.error(err);
- return res.status(401).send({ error: "Unauthorized" });
+ return res.status(401).send({ error: 'Unauthorized' });
}
}
diff --git a/packages/runtime/src/modules/debugger/routes/agent/routes.ts b/packages/runtime/src/modules/debugger/routes/agent/routes.ts
index a695569c..d3dc0a2b 100644
--- a/packages/runtime/src/modules/debugger/routes/agent/routes.ts
+++ b/packages/runtime/src/modules/debugger/routes/agent/routes.ts
@@ -1,11 +1,7 @@
-import { uploadHandler } from "@core/middlewares/uploadHandler.mw";
-import { createDebuggerRouter } from "@core/shared-agent-router";
-import agentLoader from "@debugger/middlewares/agentLoader.mw";
-import {
- createSseConnection,
- getDebugSession,
- processAgentRequest,
-} from "@debugger/services/agent-request-handler";
+import { uploadHandler } from '@core/middlewares/uploadHandler.mw';
+import { createDebuggerRouter } from '@core/shared-agent-router';
+import agentLoader from '@debugger/middlewares/agentLoader.mw';
+import { createSseConnection, getDebugSession, processAgentRequest } from '@debugger/services/agent-request-handler';
/* uploadHandler should precede agentLoader to parse multipart/form-data correctly */
const middlewares = [uploadHandler, agentLoader];
diff --git a/packages/runtime/src/modules/debugger/routes/models/router.ts b/packages/runtime/src/modules/debugger/routes/models/router.ts
index 7b0928bd..801eee19 100644
--- a/packages/runtime/src/modules/debugger/routes/models/router.ts
+++ b/packages/runtime/src/modules/debugger/routes/models/router.ts
@@ -1,33 +1,28 @@
-import { createHash } from "crypto";
-import express, { Response } from "express";
+import { createHash } from 'crypto';
+import express, { Response } from 'express';
-import {
- AccessCandidate,
- ConnectorService,
- Logger,
- ModelsProviderConnector,
-} from "@smythos/sre";
+import { AccessCandidate, ConnectorService, Logger, ModelsProviderConnector } from '@smythos/sre';
-import { teamAccessCheck } from "@debugger/middlewares/teamAccessCheck.mw";
+import { teamAccessCheck } from '@debugger/middlewares/teamAccessCheck.mw';
-const console = Logger("[Builder] Router: Models");
+const console = Logger('[Builder] Router: Models');
const router = express.Router();
// Constants
-const MODELS_HASH_KEY = "models_content_hash";
+const MODELS_HASH_KEY = 'models_content_hash';
-router.head("/", async (req, res, next) => {
+router.head('/', async (req, res, next) => {
try {
const modelsHash = await getModelsHash();
- res.setHeader("x-models-hash", modelsHash);
+ res.setHeader('x-models-hash', modelsHash);
res.status(200).send();
} catch (error) {
handleError(error, res);
}
});
-router.get("/", async (req, res, next) => {
+router.get('/', async (req, res, next) => {
try {
const models = await getModels();
const modelsHash = await getModelsHash();
@@ -37,26 +32,26 @@ router.get("/", async (req, res, next) => {
const cacheConnector = ConnectorService.getCacheConnector();
// We are intentionally not awaiting this operation, as updating the model hash does not need to block the response.
cacheConnector
- .user(AccessCandidate.user("system-smyth"))
+ .user(AccessCandidate.user('system-smyth'))
?.set(MODELS_HASH_KEY, modelsHash)
- .catch((err) => {
- console.warn("Updating models hash cache error:", err?.message || err);
+ .catch(err => {
+ console.warn('Updating models hash cache error:', err?.message || err);
});
// #endregion Cache model hash
- res.setHeader("x-models-hash", modelsHash);
+ res.setHeader('x-models-hash', modelsHash);
res.status(200).send(models);
} catch (error) {
handleError(error, res);
}
});
-router.get("/custom/:teamId", teamAccessCheck, async (req, res, next) => {
+router.get('/custom/:teamId', teamAccessCheck, async (req, res, next) => {
try {
const teamId = req.params.teamId;
if (!teamId) {
- return res.status(400).send({ error: "Team ID is required" });
+ return res.status(400).send({ error: 'Team ID is required' });
}
const models = await getCustomModels(teamId);
@@ -68,11 +63,8 @@ router.get("/custom/:teamId", teamAccessCheck, async (req, res, next) => {
});
async function getCustomModels(teamId: string): Promise<Record<string, any>> {
- const modelsProviderConnector: ModelsProviderConnector =
- ConnectorService.getModelsProviderConnector();
- const modelProviderCandidate = modelsProviderConnector.requester(
- AccessCandidate.team(teamId)
- );
+ const modelsProviderConnector: ModelsProviderConnector = ConnectorService.getModelsProviderConnector();
+ const modelProviderCandidate = modelsProviderConnector.requester(AccessCandidate.team(teamId));
const models = await modelProviderCandidate.getCustomModels();
return models;
}
@@ -80,11 +72,8 @@ async function getCustomModels(teamId: string): Promise<Record<string, any>> {
// Helper functions
async function getModels(): Promise<Record<string, any>> {
- const modelsProviderConnector: ModelsProviderConnector =
- ConnectorService.getModelsProviderConnector();
- const modelProviderCandidate = modelsProviderConnector.requester(
- AccessCandidate.user("system-smyth")
- );
+ const modelsProviderConnector: ModelsProviderConnector = ConnectorService.getModelsProviderConnector();
+ const modelProviderCandidate = modelsProviderConnector.requester(AccessCandidate.user('system-smyth'));
const models = await modelProviderCandidate.getModels();
return models;
}
@@ -92,16 +81,16 @@ async function getModels(): Promise<Record<string, any>> {
async function getModelsHash(): Promise<string> {
const models = await getModels();
const modelsString = JSON.stringify(models);
- const hash = createHash("sha256").update(modelsString).digest("hex");
+ const hash = createHash('sha256').update(modelsString).digest('hex');
return hash;
}
function handleError(error: any, res: Response): void {
- console.warn("Error in models route:", error);
+ console.warn('Error in models route:', error);
const status = error.status || 500;
- const message = error.message || "Internal server error";
+ const message = error.message || 'Internal server error';
res.status(status).send({ error: message });
}
diff --git a/packages/runtime/src/modules/debugger/services/agent-request-handler.ts b/packages/runtime/src/modules/debugger/services/agent-request-handler.ts
index b7108ed1..5cea0c7d 100644
--- a/packages/runtime/src/modules/debugger/services/agent-request-handler.ts
+++ b/packages/runtime/src/modules/debugger/services/agent-request-handler.ts
@@ -1,39 +1,25 @@
-import axios from "axios";
-import { Request } from "express";
+import axios from 'axios';
+import { Request } from 'express';
-import { AgentProcess, Logger } from "@smythos/sre";
+import { AgentProcess, Logger } from '@smythos/sre';
-import config from "@/core/config";
-import { getMockData } from "@core/helpers/agent.helper";
+import config from '@/core/config';
+import { getMockData } from '@core/helpers/agent.helper';
-const console = Logger("Service: Agent Request Handler");
+const console = Logger('Service: Agent Request Handler');
const debugPromises: any = {}; //TODO : persist this ?
export const sseConnections = new Map();
export function getDebugSession(id) {
- console.log(
- `Getting debug session for agent ${id} with session id ${debugPromises[id]?.dbgSession}`
- );
- console.log(
- `Session exists: ${
- debugPromises[id] ? "Yes" : "No"
- } and session.dbgSession exists: ${
- debugPromises[id]?.dbgSession ? "Yes" : "No"
- }`
- );
- console.log(
- `Debug sessions found for the following agents: ${Object.keys(
- debugPromises
- ).join(", ")}`
- );
+ console.log(`Getting debug session for agent ${id} with session id ${debugPromises[id]?.dbgSession}`);
+ console.log(`Session exists: ${debugPromises[id] ? 'Yes' : 'No'} and session.dbgSession exists: ${debugPromises[id]?.dbgSession ? 'Yes' : 'No'}`);
+ console.log(`Debug sessions found for the following agents: ${Object.keys(debugPromises).join(', ')}`);
return debugPromises[id]?.dbgSession;
}
export function createSseConnection(req: any) {
- const sseId =
- Math.random().toString(36).substring(2, 15) +
- Math.random().toString(36).substring(2, 15);
+ const sseId = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
const INACTIVITY_TIMEOUT = 60 * 60 * 1000; // 1 hour
const res = req.res;
const connection = { res, timeout: null };
@@ -57,7 +43,7 @@ export function createSseConnection(req: any) {
};
// Clean up when the client disconnects
- req.on("close", () => {
+ req.on('close', () => {
console.log(`Client disconnected: ${sseId}`);
sseConnections.delete(sseId);
res.end();
@@ -70,25 +56,25 @@ export async function processAgentRequest(agentId: string, req: any) {
const agentProcess = AgentProcess.load(req._agent);
if (!agentProcess) {
- return { status: 404, data: "Agent not found" };
+ return { status: 404, data: 'Agent not found' };
}
await agentProcess.ready();
//const req = agent.agentRequest;
- req.socket.on("close", () => {
+ req.socket.on('close', () => {
// console.log('Client socket closed, killing agent');
// Handle the cancellation logic
//agentProcess.agent.kill();
});
- const skipDebug = typeof req.header("X-DEBUG-SKIP") != "undefined";
- const monitorIds = req.header("X-MONITOR-ID")
+ const skipDebug = typeof req.header('X-DEBUG-SKIP') != 'undefined';
+ const monitorIds = req.header('X-MONITOR-ID')
? new Set<string>(
req
- .header("X-MONITOR-ID")
- .split(",")
- .map((id: string) => id.trim())
+ .header('X-MONITOR-ID')
+ .split(',')
+ .map((id: string) => id.trim()),
)
: undefined;
if (monitorIds) {
@@ -100,7 +86,7 @@ export async function processAgentRequest(agentId: string, req: any) {
}
}
- const readStateId: string = req.header("X-DEBUG-READ") || "";
+ const readStateId: string = req.header('X-DEBUG-READ') || '';
if (readStateId) {
try {
const result = await agentProcess.readDebugState(readStateId, {
@@ -114,7 +100,7 @@ export async function processAgentRequest(agentId: string, req: any) {
return { status: 200, data: result };
} catch (error: any) {
console.error(error);
- return { status: 400, data: "Agent State Unavailable" };
+ return { status: 400, data: 'Agent State Unavailable' };
}
}
@@ -124,10 +110,10 @@ export async function processAgentRequest(agentId: string, req: any) {
startLiveDebug =
req._agent.usingTestDomain &&
req._agent.debugSessionEnabled &&
- typeof req.header("X-DEBUG-RUN") == "undefined" &&
- typeof req.header("X-DEBUG-read") == "undefined" &&
- typeof req.header("X-DEBUG-INJ") == "undefined" &&
- typeof req.header("X-DEBUG-STOP") == "undefined";
+ typeof req.header('X-DEBUG-RUN') == 'undefined' &&
+ typeof req.header('X-DEBUG-read') == 'undefined' &&
+ typeof req.header('X-DEBUG-INJ') == 'undefined' &&
+ typeof req.header('X-DEBUG-STOP') == 'undefined';
}
// #region[mock_data]
@@ -151,21 +137,21 @@ export async function processAgentRequest(agentId: string, req: any) {
}
}
} catch (error) {
- console.warn("Error getting mock data", error);
+ console.warn('Error getting mock data', error);
}
// When we have mock data to inject, we need to set the x-mock-data-inj header
if (body?.length > 0) {
- req.headers["x-mock-data-inj"] = "";
+ req.headers['x-mock-data-inj'] = '';
}
// If the body is an empty object, we need to convert it to an array
const existingBody = Object.keys(req.body).length === 0 ? [] : req.body;
if (Array.isArray(existingBody)) {
- const existingComponentIds = existingBody?.map((item) => item.id) || [];
+ const existingComponentIds = existingBody?.map(item => item.id) || [];
- body = body.filter((item) => !existingComponentIds.includes(item.id));
+ body = body.filter(item => !existingComponentIds.includes(item.id));
req.body = [...existingBody, ...body];
}
@@ -179,23 +165,17 @@ export async function processAgentRequest(agentId: string, req: any) {
}
}
-async function runAgentProcess(
- agentId: string,
- agentProcess: AgentProcess,
- req: any
-) {
+async function runAgentProcess(agentId: string, agentProcess: AgentProcess, req: any) {
try {
//const req = agent.agentRequest;
const debugPromiseId = `${agentId}`;
- if (req.header("X-DEBUG-STOP")) {
+ if (req.header('X-DEBUG-STOP')) {
if (debugPromises[debugPromiseId]) {
- console.log(
- `Debug session for agent ${agentId} with session id ${debugPromiseId} stopped because of X-DEBUG-STOP header. DELETING PROMISE`
- );
+ console.log(`Debug session for agent ${agentId} with session id ${debugPromiseId} stopped because of X-DEBUG-STOP header. DELETING PROMISE`);
const dbgPromise: any = debugPromises[debugPromiseId];
delete debugPromises[debugPromiseId];
- dbgPromise.resolve({ status: 400, error: "Debug Session Stopped" });
+ dbgPromise.resolve({ status: 400, error: 'Debug Session Stopped' });
}
}
@@ -211,10 +191,10 @@ async function runAgentProcess(
//deployed agents have a version number
const pathMatches = req.path.match(/(^\/v[0-9]+\.[0-9]+?)?(\/api\/(.+)?)/);
if (!pathMatches || !pathMatches[2]) {
- return { status: 404, data: { error: "Endpoint not found" } };
+ return { status: 404, data: { error: 'Endpoint not found' } };
}
const endpointPath = pathMatches[2];
- const input = req.method == "GET" ? req.query : req.body;
+ const input = req.method == 'GET' ? req.query : req.body;
// const result: any = await agent.process(endpointPath, input).catch((error) => ({ error }));
const { data: result } = await agentProcess
@@ -227,10 +207,10 @@ async function runAgentProcess(
//'X-DEBUG-RUN': '',
},
})
- .catch((error) => ({ data: { error: error.toString() } }));
+ .catch(error => ({ data: { error: error.toString() } }));
if (result.error) {
- console.error("ERROR", result.error);
+ console.error('ERROR', result.error);
//res.status(500).json({ ...result, error: result.error.toString(), agentId: agent.id, agentName: agent.name });
return {
status: 500,
@@ -244,13 +224,13 @@ async function runAgentProcess(
};
}
//handle API embodiments debug response
- const dbgSession = result?.dbgSession || result?.expiredDbgSession || "";
+ const dbgSession = result?.dbgSession || result?.expiredDbgSession || '';
dbgPromise = debugPromises[debugPromiseId];
if (dbgSession && dbgPromise) {
if (result.finalResult) {
//const result = debugPromises[agent.id].result;
console.log(
- `Debug session for agent ${agentId} with session id ${debugPromiseId} resolved since the final result is available. DELETING PROMISE`
+ `Debug session for agent ${agentId} with session id ${debugPromiseId} resolved since the final result is available. DELETING PROMISE`,
);
delete debugPromises[debugPromiseId];
@@ -265,33 +245,29 @@ async function runAgentProcess(
return { status: error.response.status, data: error.response.data };
} else {
// Some other error occurred
- return { status: 500, data: "Internal Server Error" };
+ return { status: 500, data: 'Internal Server Error' };
}
}
}
-async function runAgentDebug(
- agentId: string,
- agentProcess: AgentProcess,
- req: Request
-) {
+async function runAgentDebug(agentId: string, agentProcess: AgentProcess, req: Request) {
try {
//const req = agent.agentRequest;
const debugPromiseId = `${agentId}`;
- const excludedHeaders = ["host", "content-length", "accept-encoding"];
+ const excludedHeaders = ['host', 'content-length', 'accept-encoding'];
const headers = Object.keys(req.headers)
- .filter((header) => !excludedHeaders.includes(header.toLowerCase()))
+ .filter(header => !excludedHeaders.includes(header.toLowerCase()))
.reduce((obj, header) => {
obj[header] = req.headers[header];
return obj;
}, {});
- headers["X-AGENT-ID"] = agentId;
- headers["X-DEBUG-RUN"] = "";
+ headers['X-AGENT-ID'] = agentId;
+ headers['X-DEBUG-RUN'] = '';
//'X-DEBUG-RUN': '',
const port = config.env.PORT;
- let url = `http://localhost:${port}${req.path.replace("/debug", "/api")}`;
+ let url = `http://localhost:${port}${req.path.replace('/debug', '/api')}`;
//add query params
// * query params will add with 'params' property in axios to parse Object type data properly
/* if (req.query) {
@@ -301,7 +277,7 @@ async function runAgentDebug(
url += `?${query}`;
} */
- const input = req.method == "GET" ? req.query : req.body;
+ const input = req.method == 'GET' ? req.query : req.body;
//check if request has form-data
@@ -349,7 +325,7 @@ async function runAgentDebug(
//const agentId = agent.id;
if (debugPromises[debugPromiseId]) {
console.log(
- `Tried to start a new debug session for agent ${agentId}, but a session is already running. req path ${req.path} and url ${req.url}. DELETING THE OLD PROMISE TO START A NEW ONE`
+ `Tried to start a new debug session for agent ${agentId}, but a session is already running. req path ${req.path} and url ${req.url}. DELETING THE OLD PROMISE TO START A NEW ONE`,
);
agentProcess?.agent?.sse?.close();
@@ -357,7 +333,7 @@ async function runAgentDebug(
dbgPromise.reject({
status: 400,
data: {
- error: "Debug session interrupted by another request",
+ error: 'Debug session interrupted by another request',
details: { debugPromiseId, session: dbgPromise.dbgSession },
},
});
@@ -366,7 +342,7 @@ async function runAgentDebug(
}
const sessionPromise = new Promise((resolve, reject) => {
console.log(
- `A new debug session is started for agent ${agentId} with session id ${dbgSession} and req path ${req.path} and url${req.url}. CLIENT IP: ${req.headers["x-forwarded-for"]} - ${req.socket.remoteAddress}. X-HASH-ID: ${req.headers["x-hash-id"]}`
+ `A new debug session is started for agent ${agentId} with session id ${dbgSession} and req path ${req.path} and url${req.url}. CLIENT IP: ${req.headers['x-forwarded-for']} - ${req.socket.remoteAddress}. X-HASH-ID: ${req.headers['x-hash-id']}`,
);
debugPromises[debugPromiseId] = {
dbgSession,
@@ -377,17 +353,15 @@ async function runAgentDebug(
//promise expiration
setTimeout(
() => {
- console.log(
- `Debug session for agent ${agentId} with session id ${dbgSession} expired. DELETING PROMISE`
- );
+ console.log(`Debug session for agent ${agentId} with session id ${dbgSession} expired. DELETING PROMISE`);
delete debugPromises[debugPromiseId];
- reject({ status: 500, data: "Debug Session Expired" });
+ reject({ status: 500, data: 'Debug Session Expired' });
},
- 60 * 60 * 1000 // 1 hour
+ 60 * 60 * 1000, // 1 hour
);
});
- const finalResult: any = await sessionPromise.catch((error) => ({
+ const finalResult: any = await sessionPromise.catch(error => ({
error,
}));
@@ -413,15 +387,15 @@ async function runAgentDebug(
} else {
// Some other error occurred
console.error(error);
- return { status: 500, data: "Internal Server Error" };
+ return { status: 500, data: 'Internal Server Error' };
}
}
}
-process.on("MANAGEMENT:DISABLE_PORT" as any, async () => {
+process.on('MANAGEMENT:DISABLE_PORT' as any, async () => {
// close each connection at once using promise.all
- console.log("Closing all SSE connections");
- sseConnections.forEach((connection) => {
+ console.log('Closing all SSE connections');
+ sseConnections.forEach(connection => {
connection.res.end();
});
sseConnections.clear();
diff --git a/packages/runtime/src/modules/debugger/services/component-async-ctx.ts b/packages/runtime/src/modules/debugger/services/component-async-ctx.ts
index 3fe19d6f..12d27c4d 100644
--- a/packages/runtime/src/modules/debugger/services/component-async-ctx.ts
+++ b/packages/runtime/src/modules/debugger/services/component-async-ctx.ts
@@ -3,27 +3,27 @@ import { AsyncLocalStorage } from 'async_hooks';
const asyncLocalStorage = new AsyncLocalStorage();
export const componentAsyncCtx = {
- run: async (callback, initialValue = {}) => {
- return await asyncLocalStorage.run(initialValue, callback);
- },
- enterWith: (initialValue = {}) => {
- // preserve the store (if any)
- const store = (asyncLocalStorage.getStore() as any) || {};
- return asyncLocalStorage.enterWith({ ...store, ...initialValue });
- },
- get: (key: string) => {
- const store = asyncLocalStorage.getStore();
- if (store) {
- return store[key];
- }
- return null;
- },
- set: (key: string, value: any) => {
- const store = asyncLocalStorage.getStore();
- if (store) {
- store[key] = value;
- } else {
- console.log('ComponentAsyncCtx: no store found');
- }
- },
+ run: async (callback, initialValue = {}) => {
+ return await asyncLocalStorage.run(initialValue, callback);
+ },
+ enterWith: (initialValue = {}) => {
+ // preserve the store (if any)
+ const store = (asyncLocalStorage.getStore() as any) || {};
+ return asyncLocalStorage.enterWith({ ...store, ...initialValue });
+ },
+ get: (key: string) => {
+ const store = asyncLocalStorage.getStore();
+ if (store) {
+ return store[key];
+ }
+ return null;
+ },
+ set: (key: string, value: any) => {
+ const store = asyncLocalStorage.getStore();
+ if (store) {
+ store[key] = value;
+ } else {
+ console.log('ComponentAsyncCtx: no store found');
+ }
+ },
};
diff --git a/packages/runtime/src/modules/embodiment/constants.ts b/packages/runtime/src/modules/embodiment/constants.ts
index 3462fdb0..d433511d 100644
--- a/packages/runtime/src/modules/embodiment/constants.ts
+++ b/packages/runtime/src/modules/embodiment/constants.ts
@@ -1,5 +1,5 @@
export enum EMBODIMENT_TYPES {
- ChatBot = "chatBot",
- ChatGPT = "chatGPT",
- FormPreview = "form",
+ ChatBot = 'chatBot',
+ ChatGPT = 'chatGPT',
+ FormPreview = 'form',
}
diff --git a/packages/runtime/src/modules/embodiment/helpers/agentChat.helper.ts b/packages/runtime/src/modules/embodiment/helpers/agentChat.helper.ts
index 66a50315..e99e8c4b 100644
--- a/packages/runtime/src/modules/embodiment/helpers/agentChat.helper.ts
+++ b/packages/runtime/src/modules/embodiment/helpers/agentChat.helper.ts
@@ -3,24 +3,24 @@ import { getM2MToken } from './logto.helper';
import { includeAuth, mwSysAPI } from '@core/services/smythAPIReq';
export async function updateConversation({ data, conversationId }: { conversationId: string; data: IMetadataFile }) {
- const token = (await getM2MToken('https://api.smyth.ai')) as string;
- const response = await mwSysAPI
- .put(
- `/chats/${conversationId}`,
- {
- conversation: {
- label: data.label,
- summary: data.summary,
- chunkSize: data.chunkSize,
- lastChunkID: data.lastChunkId?.toString(),
- },
- },
- includeAuth(token),
- )
- .catch((error) => {
- console.error('Error updating conversation', error);
- return null;
- });
+ const token = (await getM2MToken('https://api.smyth.ai')) as string;
+ const response = await mwSysAPI
+ .put(
+ `/chats/${conversationId}`,
+ {
+ conversation: {
+ label: data.label,
+ summary: data.summary,
+ chunkSize: data.chunkSize,
+ lastChunkID: data.lastChunkId?.toString(),
+ },
+ },
+ includeAuth(token),
+ )
+ .catch(error => {
+ console.error('Error updating conversation', error);
+ return null;
+ });
- return response?.status === 200;
+ return response?.status === 200;
}
diff --git a/packages/runtime/src/modules/embodiment/helpers/chatgpt.helper.ts b/packages/runtime/src/modules/embodiment/helpers/chatgpt.helper.ts
index 3ffc11c1..947f2467 100644
--- a/packages/runtime/src/modules/embodiment/helpers/chatgpt.helper.ts
+++ b/packages/runtime/src/modules/embodiment/helpers/chatgpt.helper.ts
@@ -1,26 +1,22 @@
-import fs from "fs";
-import path from "path";
+import fs from 'fs';
+import path from 'path';
-import { JSONContentHelper, TemplateStringHelper } from "@smythos/sre";
+import { JSONContentHelper, TemplateStringHelper } from '@smythos/sre';
-import {
- getAgentDataById,
- getAgentEmbodiments,
- getAgentIdByDomain,
-} from "@core/helpers/agent.helper";
+import { getAgentDataById, getAgentEmbodiments, getAgentIdByDomain } from '@core/helpers/agent.helper';
-import { EMBODIMENT_TYPES } from "@embodiment/constants";
-import { ChatGPTManifest } from "@embodiment/types/chatgpt.types";
+import { EMBODIMENT_TYPES } from '@embodiment/constants';
+import { ChatGPTManifest } from '@embodiment/types/chatgpt.types';
-let chatGPTDataPath = "./data/chatGPT";
+let chatGPTDataPath = './data/chatGPT';
// Path to data files differs between server ('./data/chatGPT') and tests ('../data/chatGPT').
if (process.env.TEST_ENV) {
- chatGPTDataPath = "../data/chatGPT";
+ chatGPTDataPath = '../data/chatGPT';
}
// a function that splits a string on a word boundary not exceeding a max characters length
-function splitOnSeparator(str = "", maxLen, separator = " .") {
+function splitOnSeparator(str = '', maxLen, separator = ' .') {
if (str.length <= maxLen) {
return str;
}
@@ -38,16 +34,12 @@ function splitOnSeparator(str = "", maxLen, separator = " .") {
}
//FIXME load version from prod domain
-export async function getChatGPTManifestById(
- agentId: string,
- domain: string,
- version: string
-): Promise<ChatGPTManifest> {
- console.log("getChatGPTManifestById", agentId, domain, version);
+export async function getChatGPTManifestById(agentId: string, domain: string, version: string): Promise<ChatGPTManifest> {
+ console.log('getChatGPTManifestById', agentId, domain, version);
if (!agentId) {
- throw new Error("Agent not found");
+ throw new Error('Agent not found');
}
- const agentData = await getAgentDataById(agentId, version).catch((error) => {
+ const agentData = await getAgentDataById(agentId, version).catch(error => {
console.error(error);
return { error };
});
@@ -58,52 +50,32 @@ export async function getChatGPTManifestById(
const embodiments = await getAgentEmbodiments(agentId);
// find chatgpt embodiment as we have multiple embodiments per agent
- const chatgptEmbodiment = embodiments.find(
- (embodiment: any) =>
- embodiment.type?.toLowerCase() === EMBODIMENT_TYPES.ChatGPT.toLowerCase()
- );
+ const chatgptEmbodiment = embodiments.find((embodiment: any) => embodiment.type?.toLowerCase() === EMBODIMENT_TYPES.ChatGPT.toLowerCase());
// Extract properties from the ChatGPT embodiment
const _chatgptDesctiption = chatgptEmbodiment?.properties?.modelDescription;
const _chatgptHumanName = chatgptEmbodiment?.properties?.humanName;
const _chatgptModelName = chatgptEmbodiment?.properties?.modelName;
- const _chatgptHumanDescription =
- chatgptEmbodiment?.properties?.humanDescription;
+ const _chatgptHumanDescription = chatgptEmbodiment?.properties?.humanDescription;
const _contactEmail = chatgptEmbodiment?.properties?.contactEmail;
const _legalInfoUrl = chatgptEmbodiment?.properties?.legalInfoUrl;
- const name = _chatgptHumanName || agentData.name || "Smyth Agent";
- const modelName =
- _chatgptModelName || name.replace(/ /g, "_") || "Smyth Agent";
+ const name = _chatgptHumanName || agentData.name || 'Smyth Agent';
+ const modelName = _chatgptModelName || name.replace(/ /g, '_') || 'Smyth Agent';
//data.description is deprecated, use data.shortDescription for human description and data.behavior for model description
const humanDescription = splitOnSeparator(
- _chatgptHumanDescription ||
- agentData.data.shortDescription ||
- agentData.data.description ||
- "",
+ _chatgptHumanDescription || agentData.data.shortDescription || agentData.data.description || '',
120,
- "."
- );
- const description = splitOnSeparator(
- _chatgptDesctiption ||
- agentData.data.behavior ||
- agentData.data.description ||
- "",
- 8000,
- "."
+ '.',
);
+ const description = splitOnSeparator(_chatgptDesctiption || agentData.data.behavior || agentData.data.description || '', 8000, '.');
- const icon_url =
- chatgptEmbodiment?.properties?.logoUrl ||
- "https://proxy-02.api.smyth.ai/static/img/icon.svg";
- const contact_email = _contactEmail || "";
- const legal_info_url = _legalInfoUrl || "";
+ const icon_url = chatgptEmbodiment?.properties?.logoUrl || 'https://proxy-02.api.smyth.ai/static/img/icon.svg';
+ const contact_email = _contactEmail || '';
+ const legal_info_url = _legalInfoUrl || '';
- const aiPluginTemplate = fs.readFileSync(
- path.resolve(__dirname, `${chatGPTDataPath}/ai-plugin.tpl.json`),
- "utf8"
- );
+ const aiPluginTemplate = fs.readFileSync(path.resolve(__dirname, `${chatGPTDataPath}/ai-plugin.tpl.json`), 'utf8');
let manifest = TemplateStringHelper.create(aiPluginTemplate).parse({
human_name: name,
@@ -116,29 +88,26 @@ export async function getChatGPTManifestById(
domain,
}).result;
const parsedManifest = JSONContentHelper.create(manifest).tryParse();
- manifest =
- typeof parsedManifest === "string"
- ? JSON.parse(parsedManifest)
- : parsedManifest;
+ manifest = typeof parsedManifest === 'string' ? JSON.parse(parsedManifest) : parsedManifest;
const auth = (manifest as any).auth;
const authMethod = agentData.data?.auth?.method;
const authProvider = agentData.data?.auth?.provider[authMethod];
if (authProvider) {
- if (authMethod === "oauth-oidc") {
- auth.type = "oauth";
+ if (authMethod === 'oauth-oidc') {
+ auth.type = 'oauth';
auth.client_url = `https://${domain}/oauth/authorize`;
- auth.scope = "offline_access openid profile email";
+ auth.scope = 'offline_access openid profile email';
auth.authorization_url = `https://${domain}/oauth/token`;
- auth.authorization_content_type = "application/json";
+ auth.authorization_content_type = 'application/json';
auth.verification_tokens = {
openai: authProvider?.OIDCOpenAIVerificationToken,
};
}
- if (authMethod === "api-key-bearer") {
- auth.type = "service_http";
- auth.authorization_type = "bearer";
+ if (authMethod === 'api-key-bearer') {
+ auth.type = 'service_http';
+ auth.authorization_type = 'bearer';
auth.verification_tokens = {
openai: authProvider?.BearerOpenAIVerificationToken,
};
@@ -148,13 +117,10 @@ export async function getChatGPTManifestById(
return manifest as unknown as ChatGPTManifest;
}
-export async function getChatGPTManifest(
- domain: string,
- version: string
-): Promise<ChatGPTManifest> {
+export async function getChatGPTManifest(domain: string, version: string): Promise<ChatGPTManifest> {
const agentId = await getAgentIdByDomain(domain);
if (!agentId) {
- throw new Error("Agent not found");
+ throw new Error('Agent not found');
}
return getChatGPTManifestById(agentId, domain, version);
diff --git a/packages/runtime/src/modules/embodiment/helpers/formPreview.helper.ts b/packages/runtime/src/modules/embodiment/helpers/formPreview.helper.ts
index b24f885f..cd45e6ff 100644
--- a/packages/runtime/src/modules/embodiment/helpers/formPreview.helper.ts
+++ b/packages/runtime/src/modules/embodiment/helpers/formPreview.helper.ts
@@ -1,6 +1,6 @@
-import axios, { AxiosError } from "axios";
+import axios, { AxiosError } from 'axios';
-import config from "@core/config";
+import config from '@core/config';
export type CallSkillParams = {
agentId: string;
@@ -8,8 +8,8 @@ export type CallSkillParams = {
export type CallSkillBody = {
componentId: string;
- payload?: Record<string, any> | null | "";
- version?: "dev" | "latest";
+ payload?: Record<string, any> | null | '';
+ version?: 'dev' | 'latest';
};
export type CallSkillType = {
@@ -28,20 +28,16 @@ export async function callSkill({ params, body, endpoint }: CallSkillType) {
request.body = JSON.stringify(body?.payload || {});
request.headers = {
- "Content-Type": "application/json",
- "X-DEBUG-SKIP": "true",
- ...(body.version !== "dev" && { "X-AGENT-VERSION": body.version }), // if version is dev, don't send it
- "X-AGENT-ID": params.agentId,
+ 'Content-Type': 'application/json',
+ 'X-DEBUG-SKIP': 'true',
+ ...(body.version !== 'dev' && { 'X-AGENT-VERSION': body.version }), // if version is dev, don't send it
+ 'X-AGENT-ID': params.agentId,
};
try {
- const res = await axios.post(
- `${RUNTIME_AGENT_URL}/api/${endpoint}`,
- request.body,
- {
- headers: request.headers,
- }
- );
+ const res = await axios.post(`${RUNTIME_AGENT_URL}/api/${endpoint}`, request.body, {
+ headers: request.headers,
+ });
return res.data;
} catch (error) {
const axiosErr = error as AxiosError;
diff --git a/packages/runtime/src/modules/embodiment/helpers/logto.helper.ts b/packages/runtime/src/modules/embodiment/helpers/logto.helper.ts
index 2e6c9cce..2e9c6ef4 100644
--- a/packages/runtime/src/modules/embodiment/helpers/logto.helper.ts
+++ b/packages/runtime/src/modules/embodiment/helpers/logto.helper.ts
@@ -1,19 +1,16 @@
-import axios from "axios";
-import qs from "querystring";
+import axios from 'axios';
+import qs from 'querystring';
-import config from "@core/config";
+import config from '@core/config';
//M2M test
const postData = {
- grant_type: "client_credentials",
- resource: "https://default.logto.app/api",
- scope: "all",
+ grant_type: 'client_credentials',
+ resource: 'https://default.logto.app/api',
+ scope: 'all',
};
-const base64Credentials = Buffer.from(
- `${config.env.LOGTO_M2M_APP_ID}:${config.env.LOGTO_M2M_APP_SECRET}`,
- "utf8"
-).toString("base64");
+const base64Credentials = Buffer.from(`${config.env.LOGTO_M2M_APP_ID}:${config.env.LOGTO_M2M_APP_SECRET}`, 'utf8').toString('base64');
let tokenData = {
access_token: null,
@@ -25,42 +22,42 @@ export function getM2MToken(resource?, scope?) {
}
const body = {
- grant_type: "client_credentials",
+ grant_type: 'client_credentials',
resource: resource || config.env.LOGTO_API_RESOURCE,
- scope: scope || "",
+ scope: scope || '',
};
axios({
- method: "post",
+ method: 'post',
url: `${config.env.LOGTO_SERVER}/oidc/token`,
headers: {
- Authorization: "Basic " + base64Credentials,
- "Content-Type": "application/x-www-form-urlencoded",
+ Authorization: 'Basic ' + base64Credentials,
+ 'Content-Type': 'application/x-www-form-urlencoded',
},
data: qs.stringify(body),
})
- .then((response) => {
+ .then(response => {
tokenData.access_token = response.data.access_token;
setTimeout(() => {
tokenData.access_token = null;
}, (response.data.expires_in - 100) * 1000);
resolve(tokenData.access_token);
})
- .catch((error) => {
+ .catch(error => {
reject({ error: error.response.data });
});
});
}
export async function getUserInfo(userId: string) {
- const token = await getM2MToken("https://default.logto.app/api", "all");
+ const token = await getM2MToken('https://default.logto.app/api', 'all');
const response: any = await axios({
- method: "get",
+ method: 'get',
url: `${config.env.LOGTO_SERVER}/api/users/${userId}`,
headers: {
Authorization: `Bearer ${token}`,
},
- }).catch((error) => ({ error }));
+ }).catch(error => ({ error }));
if (response.error) {
return null;
diff --git a/packages/runtime/src/modules/embodiment/helpers/openapi-adapter.helper.ts b/packages/runtime/src/modules/embodiment/helpers/openapi-adapter.helper.ts
index b6aa295e..e159bbdf 100644
--- a/packages/runtime/src/modules/embodiment/helpers/openapi-adapter.helper.ts
+++ b/packages/runtime/src/modules/embodiment/helpers/openapi-adapter.helper.ts
@@ -1,14 +1,10 @@
-import { AgentDataConnector, Logger } from "@smythos/sre";
+import { AgentDataConnector, Logger } from '@smythos/sre';
-import config from "@core/config";
-import {
- addDefaultComponentsAndConnections,
- getAgentDataById,
- getAgentIdByDomain,
-} from "@core/helpers/agent.helper";
-import type { AgentData, OpenAPISpec } from "@core/types/openapi.types";
+import config from '@core/config';
+import { addDefaultComponentsAndConnections, getAgentDataById, getAgentIdByDomain } from '@core/helpers/agent.helper';
+import type { AgentData, OpenAPISpec } from '@core/types/openapi.types';
-const console = Logger("openapi-adapter.helper.ts");
+const console = Logger('openapi-adapter.helper.ts');
/**
* AgentDataConnector implementation for sre-embodiment-server
@@ -24,10 +20,7 @@ class EmbodimentAgentDataConnector extends AgentDataConnector {
return getAgentIdByDomain(domain);
}
- async getAgentSettings(
- agentId: string,
- version?: string
- ): Promise<{ [key: string]: any }> {
+ async getAgentSettings(agentId: string, version?: string): Promise<{ [key: string]: any }> {
const agentData = await this.getAgentData(agentId, version);
return agentData?.settings || {};
}
@@ -42,24 +35,15 @@ class EmbodimentAgentDataConnector extends AgentDataConnector {
const agentData = await this.getAgentData(agentId);
return agentData?.deployed || false;
} catch (error) {
- console.warn(
- `Failed to check deployment status for agent ${agentId}:`,
- error
- );
+ console.warn(`Failed to check deployment status for agent ${agentId}:`, error);
return false;
}
}
- async listTeamAgents(
- teamId: string,
- deployedOnly?: boolean,
- includeData?: boolean
- ): Promise<AgentData[]> {
+ async listTeamAgents(teamId: string, deployedOnly?: boolean, includeData?: boolean): Promise<AgentData[]> {
// This method would need to be implemented based on your team agent retrieval logic
// For now, returning empty array as it's not used in the current OpenAPI generation
- console.warn(
- "listTeamAgents not fully implemented in EmbodimentAgentDataConnector"
- );
+ console.warn('listTeamAgents not fully implemented in EmbodimentAgentDataConnector');
return [];
}
@@ -77,17 +61,11 @@ const agentDataConnector = new EmbodimentAgentDataConnector();
*/
function constructServerUrl(domain: string): string {
const server_url_scheme =
- config.env.NODE_ENV === "development" &&
- config.env.AGENT_DOMAIN_PORT &&
- domain.includes(config.env.DEFAULT_AGENT_DOMAIN)
- ? "http"
- : "https";
+ config.env.NODE_ENV === 'development' && config.env.AGENT_DOMAIN_PORT && domain.includes(config.env.DEFAULT_AGENT_DOMAIN) ? 'http' : 'https';
const server_url_port =
- config.env.NODE_ENV === "development" &&
- config.env.AGENT_DOMAIN_PORT &&
- domain.includes(config.env.DEFAULT_AGENT_DOMAIN)
+ config.env.NODE_ENV === 'development' && config.env.AGENT_DOMAIN_PORT && domain.includes(config.env.DEFAULT_AGENT_DOMAIN)
? `:${config.env.AGENT_DOMAIN_PORT}`
- : "";
+ : '';
return `${server_url_scheme}://${domain}${server_url_port}`;
}
@@ -100,19 +78,9 @@ function constructServerUrl(domain: string): string {
* @param aiOnly - Whether to include only AI-exposed endpoints
* @returns Promise<object> - The OpenAPI specification
*/
-export async function getOpenAPIJSON(
- agent: any,
- domain: string,
- version: string,
- aiOnly: boolean = false
-): Promise<OpenAPISpec> {
+export async function getOpenAPIJSON(agent: any, domain: string, version: string, aiOnly: boolean = false): Promise<OpenAPISpec> {
const server_url = constructServerUrl(domain);
- const result = await agentDataConnector.getOpenAPIJSON(
- agent,
- server_url,
- version,
- aiOnly
- );
+ const result = await agentDataConnector.getOpenAPIJSON(agent, server_url, version, aiOnly);
return result;
}
@@ -131,21 +99,19 @@ export async function getOpenAPIJSONById(
domain: string,
version: string,
aiOnly: boolean = false,
- addDefaultFileParsingAgent: boolean = false
+ addDefaultFileParsingAgent: boolean = false,
): Promise<any> {
try {
if (!agentId) {
- return { error: "Agent not found" };
+ return { error: 'Agent not found' };
}
- const agentData = await getAgentDataById(agentId, version).catch(
- (error) => {
- console.error("Failed to fetch agent data:", error);
- return {
- error: `Failed to fetch agent data: ${error.message || error}`,
- };
- }
- );
+ const agentData = await getAgentDataById(agentId, version).catch(error => {
+ console.error('Failed to fetch agent data:', error);
+ return {
+ error: `Failed to fetch agent data: ${error.message || error}`,
+ };
+ });
if (agentData?.error) {
return agentData;
@@ -156,15 +122,10 @@ export async function getOpenAPIJSONById(
}
const server_url = constructServerUrl(domain);
- const result = await agentDataConnector.getOpenAPIJSON(
- agentData,
- server_url,
- version,
- aiOnly
- );
+ const result = await agentDataConnector.getOpenAPIJSON(agentData, server_url, version, aiOnly);
return result;
} catch (error) {
- return { error: error.message || "OpenAPI generation failed" };
+ return { error: error.message || 'OpenAPI generation failed' };
}
}
@@ -176,31 +137,18 @@ export async function getOpenAPIJSONById(
* @param addDefaultFileParsingAgent - Whether to add default file parsing components
* @returns Promise<any> - The OpenAPI specification or error
*/
-export async function getOpenAPIJSONForAI(
- domain: string,
- version: string,
- addDefaultFileParsingAgent: boolean = false
-): Promise<any> {
+export async function getOpenAPIJSONForAI(domain: string, version: string, addDefaultFileParsingAgent: boolean = false): Promise<any> {
try {
const agentId = await getAgentIdByDomain(domain);
if (!agentId) {
- return { error: "Agent not found" };
+ return { error: 'Agent not found' };
}
- return getOpenAPIJSONById(
- agentId,
- domain,
- version,
- true,
- addDefaultFileParsingAgent
- );
+ return getOpenAPIJSONById(agentId, domain, version, true, addDefaultFileParsingAgent);
} catch (error) {
- return { error: error.message || "OpenAPI generation failed" };
+ return { error: error.message || 'OpenAPI generation failed' };
}
}
// Export utility functions for backward compatibility
-export {
- getAgentDataById,
- getAgentIdByDomain,
-} from "@core/helpers/agent.helper";
+export { getAgentDataById, getAgentIdByDomain } from '@core/helpers/agent.helper';
diff --git a/packages/runtime/src/modules/embodiment/middlewares/ChatbotLoader.mw.ts b/packages/runtime/src/modules/embodiment/middlewares/ChatbotLoader.mw.ts
index 372f8ba6..cf7167a7 100644
--- a/packages/runtime/src/modules/embodiment/middlewares/ChatbotLoader.mw.ts
+++ b/packages/runtime/src/modules/embodiment/middlewares/ChatbotLoader.mw.ts
@@ -1,20 +1,18 @@
-import { Agent } from "@smythos/sre";
-import Chatbot from "../services/Chatbot.class";
-import ApiError from "../utils/apiError";
+import { Agent } from '@smythos/sre';
+import Chatbot from '../services/Chatbot.class';
+import ApiError from '../utils/apiError';
//TODO : handle cache TTL
const __chatbot_cache = { 0: 1 };
export default async function ChatbotLoader(req, res, next) {
- console.log("ChatbotLoader");
+ console.log('ChatbotLoader');
const agent: Agent = req._agent;
if (!agent) return next();
try {
if (__chatbot_cache[agent.id] && !agent.usingTestDomain) {
const chatBotData = __chatbot_cache[agent.id];
if (chatBotData.agentVersion == agent.version) {
- console.log(
- `Chatbot loaded from cache, domain=${chatBotData.domain} version=${chatBotData.version}`
- );
+ console.log(`Chatbot loaded from cache, domain=${chatBotData.domain} version=${chatBotData.version}`);
const chatbot = new Chatbot(req);
chatbot.deserialize(chatBotData);
req._chatbot = chatbot;
@@ -28,7 +26,7 @@ export default async function ChatbotLoader(req, res, next) {
__chatbot_cache[agent.id] = chatbot.serialize(); //we cannot store an object in session, so we serialize it
}
} catch (error) {
- if (error.errKey == "MODEL_NOT_SUPPORTED") {
+ if (error.errKey == 'MODEL_NOT_SUPPORTED') {
console.warn(error.message);
return next(new ApiError(400, error.message, error.errKey));
}
diff --git a/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts b/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts
index 14f783b7..093537a6 100644
--- a/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts
+++ b/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts
@@ -1,44 +1,30 @@
-import {
- Agent,
- AgentRequest,
- AgentSettings,
- ConnectorService,
- Logger,
-} from "@smythos/sre";
-
-import config from "@core/config";
-import {
- addDefaultComponentsAndConnections,
- extractAgentVerionsAndPath,
- getAgentDomainById,
- getAgentIdAndVersion,
-} from "@core/helpers/agent.helper";
-
-const console = Logger("[Embodiment] Middleware: Agent Loader");
+import { Agent, AgentRequest, AgentSettings, ConnectorService, Logger } from '@smythos/sre';
+
+import config from '@core/config';
+import { addDefaultComponentsAndConnections, extractAgentVerionsAndPath, getAgentDomainById, getAgentIdAndVersion } from '@core/helpers/agent.helper';
+
+const console = Logger('[Embodiment] Middleware: Agent Loader');
export default async function agentLoader(req, res, next) {
- console.log("agentLoader", req.path);
+ console.log('agentLoader', req.path);
const agentDataConnector = ConnectorService.getAgentDataConnector();
const isAgentLLMCall = req.body.model ? true : false;
- const agentFromModel: any = isAgentLLMCall
- ? getAgentIdAndVersion(req.body.model)
- : {};
+ const agentFromModel: any = isAgentLLMCall ? getAgentIdAndVersion(req.body.model) : {};
- if (req.path.startsWith("/static/")) {
+ if (req.path.startsWith('/static/')) {
return next();
}
- let agentId = req.header("X-AGENT-ID") || agentFromModel.agentId;
- let agentVersion =
- req.header("X-AGENT-VERSION") || agentFromModel.version || "";
- const isAgentChatRequest = req.header("x-conversation-id") !== undefined;
+ let agentId = req.header('X-AGENT-ID') || agentFromModel.agentId;
+ let agentVersion = req.header('X-AGENT-VERSION') || agentFromModel.version || '';
+ const isAgentChatRequest = req.header('x-conversation-id') !== undefined;
const debugHeader =
- req.header("X-DEBUG-STOP") !== undefined ||
- req.header("X-DEBUG-RUN") !== undefined ||
- req.header("X-DEBUG-INJ") !== undefined ||
- req.header("X-DEBUG-READ") !== undefined;
+ req.header('X-DEBUG-STOP') !== undefined ||
+ req.header('X-DEBUG-RUN') !== undefined ||
+ req.header('X-DEBUG-INJ') !== undefined ||
+ req.header('X-DEBUG-READ') !== undefined;
- let agentDomain: any = "";
+ let agentDomain: any = '';
let isTestDomain = false;
let { path, version } = extractAgentVerionsAndPath(req.path);
if (!version) version = agentVersion;
@@ -48,17 +34,15 @@ export default async function agentLoader(req, res, next) {
try {
const result = agentDataConnector?.getAgentIdByDomain?.(domain);
- if (result && typeof result.catch === "function") {
- agentId = await result.catch((error) => {
+ if (result && typeof result.catch === 'function') {
+ agentId = await result.catch(error => {
console.error(error);
});
} else {
- console.error(
- "getAgentIdByDomain method is not available or does not return a promise"
- );
+ console.error('getAgentIdByDomain method is not available or does not return a promise');
}
} catch (error) {
- console.error("Error calling getAgentIdByDomain:", error);
+ console.error('Error calling getAgentIdByDomain:', error);
}
agentDomain = domain;
if (agentId && domain.includes(config.env.DEFAULT_AGENT_DOMAIN)) {
@@ -66,39 +50,32 @@ export default async function agentLoader(req, res, next) {
}
}
if (agentId) {
- if (!isTestDomain && agentId && req.hostname.includes("localhost")) {
- console.log(
- `Host ${req.hostname} is using debug session. Assuming test domain`
- );
+ if (!isTestDomain && agentId && req.hostname.includes('localhost')) {
+ console.log(`Host ${req.hostname} is using debug session. Assuming test domain`);
isTestDomain = true;
}
if (agentDomain && !isTestDomain && !version) {
//when using a production domain but no version is specified, use latest
- version = "latest";
+ version = 'latest';
}
let agentData;
try {
const result = agentDataConnector?.getAgentData?.(agentId, version);
- if (result && typeof result.catch === "function") {
- agentData = await result.catch((error) => {
+ if (result && typeof result.catch === 'function') {
+ agentData = await result.catch(error => {
console.error(error);
return { error: error.message };
});
} else {
- console.error(
- "getAgentData method is not available or does not return a promise"
- );
- agentData = { error: "getAgentData method is not available" };
+ console.error('getAgentData method is not available or does not return a promise');
+ agentData = { error: 'getAgentData method is not available' };
}
} catch (error) {
- console.error("Error calling getAgentData:", error);
+ console.error('Error calling getAgentData:', error);
agentData = { error: error.message };
}
- if (
- isAgentChatRequest &&
- (path.startsWith("/stream") || path.startsWith("/chat-stream"))
- ) {
+ if (isAgentChatRequest && (path.startsWith('/stream') || path.startsWith('/chat-stream'))) {
// only add default components and connections for file parsing agent on chat requests
addDefaultComponentsAndConnections(agentData);
}
@@ -112,7 +89,7 @@ export default async function agentLoader(req, res, next) {
req._agent = new Agent(agentId, agentData, agentSettings, agentRequest);
req._rawAgent = agentData;
- req.socket.on("close", () => {
+ req.socket.on('close', () => {
// console.log('Client socket closed, killing agent');
// Handle the cancellation logic
//req._agent.kill();
@@ -123,23 +100,17 @@ export default async function agentLoader(req, res, next) {
req._agent.auth = agentData?.data?.auth || {};
if (!isTestDomain && req._agent.debugSessionEnabled && debugHeader) {
- console.log(
- `Host ${req.hostname} is using debug session. Assuming test domain.#2`
- );
+ console.log(`Host ${req.hostname} is using debug session. Assuming test domain.#2`);
isTestDomain = true;
}
req._agent.usingTestDomain = isTestDomain;
- req._agent.domain = isAgentLLMCall
- ? "AgentLLM"
- : agentDomain || (await getAgentDomainById(agentId));
+ req._agent.domain = isAgentLLMCall ? 'AgentLLM' : agentDomain || (await getAgentDomainById(agentId));
// req._agent.version = version;
req._agentVersion = version;
//req._data1 = 1;
- console.log(
- `Loaded Agent:${agentId} v=${version} path=${path} isTestDomain=${isTestDomain} domain=${agentDomain}`
- );
+ console.log(`Loaded Agent:${agentId} v=${version} path=${path} isTestDomain=${isTestDomain} domain=${agentDomain}`);
return next();
}
@@ -150,9 +121,7 @@ export default async function agentLoader(req, res, next) {
function cleanAgentData(agentData) {
if (agentData) {
// remove Note components
- agentData.data.components = agentData.data.components.filter(
- (c) => c.name != "Note"
- );
+ agentData.data.components = agentData.data.components.filter(c => c.name != 'Note');
// remove templateInfo
delete agentData.data?.templateInfo;
diff --git a/packages/runtime/src/modules/embodiment/modules/API/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/API/routes/router.ts
index 61b07608..833d5de8 100644
--- a/packages/runtime/src/modules/embodiment/modules/API/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/API/routes/router.ts
@@ -1,8 +1,8 @@
-import { Agent } from "@smythos/sre";
-import express from "express";
+import { Agent } from '@smythos/sre';
+import express from 'express';
-import { getOpenAPIJSON } from "@embodiment/helpers/openapi-adapter.helper";
-import agentLoader from "@embodiment/middlewares/agentLoader.mw";
+import { getOpenAPIJSON } from '@embodiment/helpers/openapi-adapter.helper';
+import agentLoader from '@embodiment/middlewares/agentLoader.mw';
const router = express.Router();
@@ -14,12 +14,7 @@ const openapiJSONHandler = async (req, res) => {
//FIXME : use the right version depending on domain [FIXED]
// const version = isTestDomain ? '' : 'latest';
- const openAPIObj = await getOpenAPIJSON(
- req._rawAgent,
- domain,
- req._agentVersion,
- false
- ).catch((error) => {
+ const openAPIObj = await getOpenAPIJSON(req._rawAgent, domain, req._agentVersion, false).catch(error => {
console.error(error);
return { error: error.message };
});
@@ -28,7 +23,7 @@ const openapiJSONHandler = async (req, res) => {
return res.status(500).send({ error: openAPIObj.error });
}
//set application type to json
- res.setHeader("Content-Type", "application/json");
+ res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(openAPIObj, null, 2));
};
@@ -39,12 +34,7 @@ const openapiJSON4LLMHandler = async (req, res) => {
//FIXME : use the right version depending on domain [FIXED]
// const version = isTestDomain ? '' : 'latest';
- const openAPIObj = await getOpenAPIJSON(
- req._rawAgent,
- domain,
- req._agentVersion,
- true
- ).catch((error) => {
+ const openAPIObj = await getOpenAPIJSON(req._rawAgent, domain, req._agentVersion, true).catch(error => {
console.error(error);
return { error: error.message };
});
@@ -53,13 +43,13 @@ const openapiJSON4LLMHandler = async (req, res) => {
return res.status(500).send({ error: openAPIObj.error });
}
//set application type to json
- res.setHeader("Content-Type", "application/json");
+ res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(openAPIObj, null, 2));
};
-router.get("/api-docs/openapi.json", agentLoader, openapiJSONHandler);
-router.get("/api-docs/openapi-llm.json", agentLoader, openapiJSON4LLMHandler);
+router.get('/api-docs/openapi.json', agentLoader, openapiJSONHandler);
+router.get('/api-docs/openapi-llm.json', agentLoader, openapiJSON4LLMHandler);
//legacy
-router.get("/.well-known/openapi.json", agentLoader, openapiJSONHandler);
+router.get('/.well-known/openapi.json', agentLoader, openapiJSONHandler);
export { router as apiRouter };
diff --git a/packages/runtime/src/modules/embodiment/modules/agentChat/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/agentChat/routes/router.ts
index eb566371..17566fc1 100644
--- a/packages/runtime/src/modules/embodiment/modules/agentChat/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/agentChat/routes/router.ts
@@ -1,17 +1,17 @@
-import express from "express";
-import Joi from "joi";
+import express from 'express';
+import Joi from 'joi';
-import config from "@core/config";
-import { getM2MToken } from "@core/helpers/logto.helper";
-import UserAgentAccessCheck from "@core/middlewares/userAgentAccessCheck.mw";
-import { validate } from "@core/middlewares/validate.mw";
-import { requestContext } from "@core/services/request-context";
-import { includeAuth, mwSysAPI } from "@core/services/smythAPIReq";
+import config from '@core/config';
+import { getM2MToken } from '@core/helpers/logto.helper';
+import UserAgentAccessCheck from '@core/middlewares/userAgentAccessCheck.mw';
+import { validate } from '@core/middlewares/validate.mw';
+import { requestContext } from '@core/services/request-context';
+import { includeAuth, mwSysAPI } from '@core/services/smythAPIReq';
-import agentLoader from "@embodiment/middlewares/agentLoader.mw";
-import ChatbotLoader from "@embodiment/middlewares/ChatbotLoader.mw";
-import Chatbot from "@embodiment/services/Chatbot.class";
-import { buildConversationId } from "@embodiment/utils/chat.utils";
+import agentLoader from '@embodiment/middlewares/agentLoader.mw';
+import ChatbotLoader from '@embodiment/middlewares/ChatbotLoader.mw';
+import Chatbot from '@embodiment/services/Chatbot.class';
+import { buildConversationId } from '@embodiment/utils/chat.utils';
// Import ChatbotResponse type for proper typing
type ChatbotResponse = {
@@ -35,8 +35,8 @@ router.use(middlewares);
let localAgentAuthorizations = {
//FIXME : this seems like a hardcoded value used by Arslan during implementation, should we remove it ?
clzi8yw441kcfblqz6zj9bv1h: {
- verifiedKey: "SomeRandomToken",
- authMethod: "api-key-bearer",
+ verifiedKey: 'SomeRandomToken',
+ authMethod: 'api-key-bearer',
},
};
@@ -47,16 +47,16 @@ const validations = {
dateRange: Joi.string()
.optional()
.regex(/^\d+,\d+$/)
- .message("Invalid date range. Expected format: timestamp,timestamp"),
+ .message('Invalid date range. Expected format: timestamp,timestamp'),
// e.g test, prod (enum)
- env: Joi.string().valid("test", "prod").required(),
+ env: Joi.string().valid('test', 'prod').required(),
}),
},
};
-router.post("/stream", async (req, res) => {
+router.post('/stream', async (req, res) => {
let streamStarted = false;
- const isLocalAgent = req.hostname.includes("localagent");
+ const isLocalAgent = req.hostname.includes('localagent');
const agentId = req._agent?.id;
const agentVersion = req._agent?.version;
let verifiedKey = null;
@@ -71,20 +71,20 @@ router.post("/stream", async (req, res) => {
try {
const { message } = req.body;
if (!req._chatbot) {
- return res.status(404).send({ error: "Chatbot not found" });
+ return res.status(404).send({ error: 'Chatbot not found' });
}
const chatbot: Chatbot = req._chatbot;
- const userId = req.header("x-user-id") || "none";
- const teamId = req.header("x-team-id") || "none";
- const isAgentChatRequest = req.header("x-conversation-id") !== undefined;
- chatbot.conversationID = req.header("x-conversation-id") || req.sessionID;
+ const userId = req.header('x-user-id') || 'none';
+ const teamId = req.header('x-team-id') || 'none';
+ const isAgentChatRequest = req.header('x-conversation-id') !== undefined;
+ chatbot.conversationID = req.header('x-conversation-id') || req.sessionID;
const headers: any = {};
if (verifiedKey) {
- headers["Authorization"] = `Bearer ${verifiedKey}`;
+ headers['Authorization'] = `Bearer ${verifiedKey}`;
}
- console.log("headers", {
+ console.log('headers', {
userId,
teamId,
conver: chatbot.conversationID,
@@ -93,18 +93,18 @@ router.post("/stream", async (req, res) => {
const dataPath = config.env.DATA_PATH;
if (!dataPath) {
- return res.status(500).send({ error: "Data path is not set" });
+ return res.status(500).send({ error: 'Data path is not set' });
}
//set response headers
- res.setHeader("Content-Type", "text/event-stream");
- res.setHeader("Cache-Control", "no-cache");
- res.setHeader("Connection", "keep-alive");
+ res.setHeader('Content-Type', 'text/event-stream');
+ res.setHeader('Cache-Control', 'no-cache');
+ res.setHeader('Connection', 'keep-alive');
//const headers = { 'X-AGENT-ID': agentId, 'X-AGENT-VERSION': agentVersion };
- headers["X-AGENT-ID"] = undefined; // because we don't debug with agent chat and this is required to make sre-runtime call the agent via http
- headers["X-AGENT-VERSION"] = agentVersion;
- headers["x-conversation-id"] = chatbot.conversationID;
+ headers['X-AGENT-ID'] = undefined; // because we don't debug with agent chat and this is required to make sre-runtime call the agent via http
+ headers['X-AGENT-VERSION'] = agentVersion;
+ headers['x-conversation-id'] = chatbot.conversationID;
await chatbot.getChatStreaming({
message,
@@ -122,9 +122,9 @@ router.post("/stream", async (req, res) => {
console.error(error);
if (!streamStarted) {
res.status(500).send({
- content: error?.message || "An error occurred. Please try again later.",
+ content: error?.message || 'An error occurred. Please try again later.',
isError: true,
- errorType: "api_error",
+ errorType: 'api_error',
});
} else {
// Stream error message in the same format as normal responses
@@ -132,34 +132,31 @@ router.post("/stream", async (req, res) => {
JSON.stringify({
content: "I'm not able to contact the server. Please try again.",
isError: true,
- errorType: "connection_error",
- })
+ errorType: 'connection_error',
+ }),
);
res.end();
}
}
});
-router.post("/new", async (req, res) => {
+router.post('/new', async (req, res) => {
const { conversation = {} } = req.body;
- const isTestDomain = req.hostname.includes(
- `.${config.env.DEFAULT_AGENT_DOMAIN}`
- );
- let agentId = req.header("X-AGENT-ID");
+ const isTestDomain = req.hostname.includes(`.${config.env.DEFAULT_AGENT_DOMAIN}`);
+ let agentId = req.header('X-AGENT-ID');
const teamDetails = requestContext.get(`team_info:${agentId}`);
- if (!teamDetails?.teamId)
- return res.status(400).send({ error: "Internal server error" });
+ if (!teamDetails?.teamId) return res.status(400).send({ error: 'Internal server error' });
// const conversationId = buildConversationId(undefined, isTestDomain);
try {
- const token = (await getM2MToken("https://api.smyth.ai")) as string;
+ const token = (await getM2MToken('https://api.smyth.ai')) as string;
const response = await mwSysAPI.post(
- "/chats",
+ '/chats',
{
conversation: {
- label: conversation.label || "Untitled Chat",
- summary: conversation.summary || "",
+ label: conversation.label || 'Untitled Chat',
+ summary: conversation.summary || '',
teamId: teamDetails.teamId,
ownerId: conversation.ownerId || undefined,
aiAgentId: agentId,
@@ -167,12 +164,9 @@ router.post("/new", async (req, res) => {
lastChunkID: conversation?.lastChunkID || undefined,
},
},
- includeAuth(token)
- );
- const conversationId = buildConversationId(
- response.data?.conversation?.id,
- isTestDomain
+ includeAuth(token),
);
+ const conversationId = buildConversationId(response.data?.conversation?.id, isTestDomain);
const finalResponse = {
...(response.data?.conversation || {}),
@@ -187,72 +181,65 @@ router.post("/new", async (req, res) => {
});
//* NOTE THAT THIS ROUTE IS PROTECTED BY UserAgentAccessCheck middleware AND IT SHOULD ALWAYS BE PROTECTED
-router.post(
- "/export-conversations",
- validate(validations.exportConversations),
- async (req, res) => {
- const agentId = req._agent?.id;
- if (!agentId) {
- return res.status(400).send({ error: "agentId is required" });
- }
- const { dateRange, env } = req.body;
- const chatbot = req._chatbot;
+router.post('/export-conversations', validate(validations.exportConversations), async (req, res) => {
+ const agentId = req._agent?.id;
+ if (!agentId) {
+ return res.status(400).send({ error: 'agentId is required' });
+ }
+ const { dateRange, env } = req.body;
+ const chatbot = req._chatbot;
- let responseStarted = false;
+ let responseStarted = false;
- try {
- // Set headers before starting the response
- res.setHeader("Content-Type", "application/json");
- res.setHeader(
- "Content-Disposition",
- 'attachment; filename="chat-export.json"'
- );
+ try {
+ // Set headers before starting the response
+ res.setHeader('Content-Type', 'application/json');
+ res.setHeader('Content-Disposition', 'attachment; filename="chat-export.json"');
+
+ res.write('[');
+ responseStarted = true;
+
+ let first = true;
+ for await (const convJson of chatbot.exportAllConversations({
+ dateRange,
+ env,
+ })) {
+ if (!first) res.write(',');
+ res.write(`{"convId": "${convJson.convId}", "history": `);
+ await new Promise((resolve, reject) => {
+ convJson.stream.pipe(res, { end: false });
+ convJson.stream.on('end', resolve);
+ convJson.stream.on('error', reject);
+ });
+ res.write('}');
+ first = false;
+ }
- res.write("[");
- responseStarted = true;
-
- let first = true;
- for await (const convJson of chatbot.exportAllConversations({
- dateRange,
- env,
- })) {
- if (!first) res.write(",");
- res.write(`{"convId": "${convJson.convId}", "history": `);
- await new Promise((resolve, reject) => {
- convJson.stream.pipe(res, { end: false });
- convJson.stream.on("end", resolve);
- convJson.stream.on("error", reject);
- });
- res.write("}");
- first = false;
- }
+ res.write(']');
+ res.end();
+ } catch (err) {
+ console.error('Export failed:', err);
- res.write("]");
- res.end();
- } catch (err) {
- console.error("Export failed:", err);
-
- if (!responseStarted) {
- // If response hasn't started, we can send a proper error response
- return res.status(500).json({ error: "Failed to export chat history" });
- } else {
- // If response has started, we need to end it gracefully
- try {
- if (!res.headersSent) {
- res.status(500);
- }
- res.write("]}"); // Close the JSON array properly
- res.end();
- } catch (endError) {
- console.error("Error ending response:", endError);
- // Force end the response if possible
- if (!res.destroyed) {
- res.destroy();
- }
+ if (!responseStarted) {
+ // If response hasn't started, we can send a proper error response
+ return res.status(500).json({ error: 'Failed to export chat history' });
+ } else {
+ // If response has started, we need to end it gracefully
+ try {
+ if (!res.headersSent) {
+ res.status(500);
+ }
+ res.write(']}'); // Close the JSON array properly
+ res.end();
+ } catch (endError) {
+ console.error('Error ending response:', endError);
+ // Force end the response if possible
+ if (!res.destroyed) {
+ res.destroy();
}
}
}
}
-);
+});
export { router as agentChatRouter };
diff --git a/packages/runtime/src/modules/embodiment/modules/alexa/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/alexa/routes/router.ts
index 10ff1886..3b736ecd 100644
--- a/packages/runtime/src/modules/embodiment/modules/alexa/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/alexa/routes/router.ts
@@ -1,22 +1,14 @@
-import { Agent } from "@smythos/sre";
-import express from "express";
+import { Agent } from '@smythos/sre';
+import express from 'express';
-import {
- DEFAULT_AGENT_MODEL_SETTINGS_KEY,
- DEFAULT_MODEL,
-} from "@core/constants";
+import { DEFAULT_AGENT_MODEL_SETTINGS_KEY, DEFAULT_MODEL } from '@core/constants';
-import agentLoader from "@embodiment/middlewares/agentLoader.mw";
+import agentLoader from '@embodiment/middlewares/agentLoader.mw';
-import {
- createAlexaSkill,
- handleAlexaRequest,
- isAlexaEnabled,
- parseAlexaRequest,
-} from "../services/alexa.service";
+import { createAlexaSkill, handleAlexaRequest, isAlexaEnabled, parseAlexaRequest } from '../services/alexa.service';
const router = express.Router();
-router.post("/", agentLoader, async (req: any, res) => {
+router.post('/', agentLoader, async (req: any, res) => {
try {
const agent: Agent = req._agent;
await agent.agentSettings?.ready();
@@ -25,16 +17,9 @@ router.post("/", agentLoader, async (req: any, res) => {
await agent.agentSettings?.embodiments?.ready();
const alexRequest = parseAlexaRequest(req.body);
- const model =
- agent.agentSettings?.get(DEFAULT_AGENT_MODEL_SETTINGS_KEY) ||
- DEFAULT_MODEL;
+ const model = agent.agentSettings?.get(DEFAULT_AGENT_MODEL_SETTINGS_KEY) || DEFAULT_MODEL;
- const response = await handleAlexaRequest(
- agent,
- alexRequest,
- model,
- isEnabled
- );
+ const response = await handleAlexaRequest(agent, alexRequest, model, isEnabled);
res.json(response);
} catch (error: any) {
@@ -43,24 +28,24 @@ router.post("/", agentLoader, async (req: any, res) => {
}
});
-router.post("/publish", agentLoader, async (req: any, res) => {
+router.post('/publish', agentLoader, async (req: any, res) => {
try {
const agent: Agent = req._agent;
const agentName = agent.name;
const agentDomain = agent.domain;
let accessToken = req.body.accessToken;
let vendorId = req.body.vendorId;
- const scheme = agentDomain.includes(":") ? "http" : "https";
+ const scheme = agentDomain.includes(':') ? 'http' : 'https';
let endpoint = `${scheme}://${agentDomain}/alexa`;
await createAlexaSkill(agentName, accessToken, vendorId, endpoint);
return res.json({
success: true,
- message: "Agent published to Alexa successfully",
+ message: 'Agent published to Alexa successfully',
});
} catch (error: any) {
- console.error("Error publishing to Alexa:", error);
+ console.error('Error publishing to Alexa:', error);
return res.status(500).json({ success: false, error: error.message });
}
});
diff --git a/packages/runtime/src/modules/embodiment/modules/alexa/services/alexa.service.ts b/packages/runtime/src/modules/embodiment/modules/alexa/services/alexa.service.ts
index 21551ddd..f3873edd 100644
--- a/packages/runtime/src/modules/embodiment/modules/alexa/services/alexa.service.ts
+++ b/packages/runtime/src/modules/embodiment/modules/alexa/services/alexa.service.ts
@@ -1,30 +1,19 @@
-import { getOpenAPIJSONForAI } from "@embodiment/helpers/openapi-adapter.helper";
-import { Agent, Conversation } from "@smythos/sre";
-import axios from "axios";
-const SPEAKABLE_FORMAT_PROMPT = "Return the response in speakable format";
-const ALEXA_BASE_URL = "https://api.amazonalexa.com";
-const ALEXA_SETTINGS_KEY = "alexa";
+import { getOpenAPIJSONForAI } from '@embodiment/helpers/openapi-adapter.helper';
+import { Agent, Conversation } from '@smythos/sre';
+import axios from 'axios';
+const SPEAKABLE_FORMAT_PROMPT = 'Return the response in speakable format';
+const ALEXA_BASE_URL = 'https://api.amazonalexa.com';
+const ALEXA_SETTINGS_KEY = 'alexa';
-export async function handleAlexaRequest(
- agent: Agent,
- alexRequest: any,
- model: string,
- isEnabled: boolean
-) {
+export async function handleAlexaRequest(agent: Agent, alexRequest: any, model: string, isEnabled: boolean) {
if (!isEnabled) {
- return buildAlexaResponse("Alexa is not enabled for this agent");
+ return buildAlexaResponse('Alexa is not enabled for this agent');
}
- if (alexRequest.type === "LaunchRequest") {
- return buildAlexaResponse(
- "Hi I am smythos agent. What can I help you with?"
- );
+ if (alexRequest.type === 'LaunchRequest') {
+ return buildAlexaResponse('Hi I am smythos agent. What can I help you with?');
}
const searchQuery = alexRequest.slots.searchQuery.heardAs;
- const agentResponse = await processAlexaSearchQuery(
- searchQuery,
- model,
- agent
- );
+ const agentResponse = await processAlexaSearchQuery(searchQuery, model, agent);
const response = buildAlexaResponse(agentResponse);
return response;
}
@@ -39,7 +28,7 @@ export function parseAlexaRequest(alexRequest: any) {
export function getSlotValues(filledSlots) {
const slotValues = {};
- Object.keys(filledSlots).forEach((item) => {
+ Object.keys(filledSlots).forEach(item => {
const name = filledSlots[item].name;
if (
@@ -49,23 +38,19 @@ export function getSlotValues(filledSlots) {
filledSlots[item].resolutions.resolutionsPerAuthority[0].status &&
filledSlots[item].resolutions.resolutionsPerAuthority[0].status.code
) {
- switch (
- filledSlots[item].resolutions.resolutionsPerAuthority[0].status.code
- ) {
- case "ER_SUCCESS_MATCH":
+ switch (filledSlots[item].resolutions.resolutionsPerAuthority[0].status.code) {
+ case 'ER_SUCCESS_MATCH':
slotValues[name] = {
heardAs: filledSlots[item].value,
- resolved:
- filledSlots[item].resolutions.resolutionsPerAuthority[0].values[0]
- .value.name,
- ERstatus: "ER_SUCCESS_MATCH",
+ resolved: filledSlots[item].resolutions.resolutionsPerAuthority[0].values[0].value.name,
+ ERstatus: 'ER_SUCCESS_MATCH',
};
break;
- case "ER_SUCCESS_NO_MATCH":
+ case 'ER_SUCCESS_NO_MATCH':
slotValues[name] = {
heardAs: filledSlots[item].value,
- resolved: "",
- ERstatus: "ER_SUCCESS_NO_MATCH",
+ resolved: '',
+ ERstatus: 'ER_SUCCESS_NO_MATCH',
};
break;
default:
@@ -73,9 +58,9 @@ export function getSlotValues(filledSlots) {
}
} else {
slotValues[name] = {
- heardAs: filledSlots[item].value || "", // may be null
- resolved: "",
- ERstatus: "",
+ heardAs: filledSlots[item].value || '', // may be null
+ resolved: '',
+ ERstatus: '',
};
}
}, this);
@@ -83,22 +68,18 @@ export function getSlotValues(filledSlots) {
return slotValues;
}
-export function buildAlexaResponse(
- outputSpeech: string,
- reprompt = "",
- shouldEndSession = false
-) {
+export function buildAlexaResponse(outputSpeech: string, reprompt = '', shouldEndSession = false) {
return {
- version: "1.0",
+ version: '1.0',
sessionAttributes: {},
response: {
outputSpeech: {
- type: "PlainText",
+ type: 'PlainText',
text: outputSpeech,
},
reprompt: {
outputSpeech: {
- type: "PlainText",
+ type: 'PlainText',
text: reprompt,
},
},
@@ -107,19 +88,14 @@ export function buildAlexaResponse(
};
}
-export async function createAlexaSkill(
- agentName: string,
- accessToken: string,
- vendorId: string,
- endpoint: string
-) {
+export async function createAlexaSkill(agentName: string, accessToken: string, vendorId: string, endpoint: string) {
try {
const response = await axios({
- method: "post",
+ method: 'post',
url: `${ALEXA_BASE_URL}/v1/skills`,
headers: {
- Authorization: "Bearer " + accessToken,
- "Content-Type": "application/json",
+ Authorization: 'Bearer ' + accessToken,
+ 'Content-Type': 'application/json',
},
data: {
vendorId: vendorId,
@@ -127,23 +103,23 @@ export async function createAlexaSkill(
apis: {
custom: {
endpoint: {
- sslCertificateType: "Wildcard",
+ sslCertificateType: 'Wildcard',
uri: endpoint,
},
interfaces: [],
locales: {},
},
},
- manifestVersion: "1.0",
+ manifestVersion: '1.0',
publishingInformation: {
- category: "ORGANIZERS_AND_ASSISTANTS",
+ category: 'ORGANIZERS_AND_ASSISTANTS',
locales: {
- "en-US": {
- description: "Smythos agent",
- examplePhrases: ["Alexa open " + agentName],
+ 'en-US': {
+ description: 'Smythos agent',
+ examplePhrases: ['Alexa open ' + agentName],
keywords: [agentName],
name: agentName,
- summary: "invoke " + agentName,
+ summary: 'invoke ' + agentName,
},
},
},
@@ -151,14 +127,14 @@ export async function createAlexaSkill(
},
});
const skillId = response.data.skillId;
- await new Promise((resolve) => setTimeout(resolve, 2000));
+ await new Promise(resolve => setTimeout(resolve, 2000));
await axios({
- method: "put",
+ method: 'put',
url: `${ALEXA_BASE_URL}/v1/skills/${skillId}/stages/development/interactionModel/locales/en-US`,
headers: {
- Authorization: "Bearer " + accessToken,
- "Content-Type": "application/json",
+ Authorization: 'Bearer ' + accessToken,
+ 'Content-Type': 'application/json',
},
data: {
interactionModel: {
@@ -166,34 +142,34 @@ export async function createAlexaSkill(
invocationName: agentName.toLowerCase(),
intents: [
{
- name: "AMAZON.CancelIntent",
+ name: 'AMAZON.CancelIntent',
samples: [],
},
{
- name: "AMAZON.HelpIntent",
+ name: 'AMAZON.HelpIntent',
samples: [],
},
{
- name: "AMAZON.StopIntent",
+ name: 'AMAZON.StopIntent',
samples: [],
},
{
- name: "AMAZON.FallbackIntent",
+ name: 'AMAZON.FallbackIntent',
samples: [],
},
{
- name: "AMAZON.NavigateHomeIntent",
+ name: 'AMAZON.NavigateHomeIntent',
samples: [],
},
{
- name: "SmythosQuery",
+ name: 'SmythosQuery',
slots: [
{
- name: "searchQuery",
- type: "AMAZON.SearchQuery",
+ name: 'searchQuery',
+ type: 'AMAZON.SearchQuery',
},
],
- samples: ["Hi {searchQuery}", "Hello {searchQuery}"],
+ samples: ['Hi {searchQuery}', 'Hello {searchQuery}'],
},
],
types: [],
@@ -207,42 +183,34 @@ export async function createAlexaSkill(
}
}
-export function processAlexaSearchQuery(
- query: string,
- model: string,
- agent: Agent
-): Promise<string> {
+export function processAlexaSearchQuery(query: string, model: string, agent: Agent): Promise<string> {
return new Promise(async (resolve, reject) => {
// const { agentId, agentVersion } = getAgentIdAndVersion(model);
- let result = "";
- const spec = await getOpenAPIJSONForAI(
- agent.domain,
- agent.usingTestDomain ? "" : "latest",
- false
- );
+ let result = '';
+ const spec = await getOpenAPIJSONForAI(agent.domain, agent.usingTestDomain ? '' : 'latest', false);
// Adapt the model based on the user's plan, especially to support certain OpenAI models for legacy users with limited tokens without their own API key.
const conversation = new Conversation(model, spec, {
agentId: agent.id,
});
- conversation.on("error", (error) => {
- console.error("Error in conversation:", error);
+ conversation.on('error', error => {
+ console.error('Error in conversation:', error);
throw `An error occurred. Please try again later or select a different model.`;
});
- conversation.on("content", (content) => {
+ conversation.on('content', content => {
try {
- if (content?.indexOf("}{") >= 0) {
- content = content.replace(/}{/g, "} {");
+ if (content?.indexOf('}{') >= 0) {
+ content = content.replace(/}{/g, '} {');
}
result += content;
} catch (e) {}
});
- conversation.on("end", () => {
- console.log("streaming: [DONE]");
+ conversation.on('end', () => {
+ console.log('streaming: [DONE]');
resolve(result);
});
conversation.streamPrompt(`${query} ${SPEAKABLE_FORMAT_PROMPT}`, {
- "X-AGENT-ID": agent.id,
+ 'X-AGENT-ID': agent.id,
});
});
}
@@ -251,5 +219,5 @@ export function isAlexaEnabled(agent: Agent) {
if (agent.usingTestDomain) {
return true;
}
- return agent.agentSettings?.get(ALEXA_SETTINGS_KEY) === "true";
+ return agent.agentSettings?.get(ALEXA_SETTINGS_KEY) === 'true';
}
diff --git a/packages/runtime/src/modules/embodiment/modules/chatGPT/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/chatGPT/routes/router.ts
index 1b334e14..80a6c713 100644
--- a/packages/runtime/src/modules/embodiment/modules/chatGPT/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/chatGPT/routes/router.ts
@@ -1,46 +1,32 @@
-import { getChatGPTManifest } from "@embodiment/helpers/chatgpt.helper";
-import { getOpenAPIJSON } from "@embodiment/helpers/openapi-adapter.helper";
-import agentLoader from "@embodiment/middlewares/agentLoader.mw";
-import express from "express";
+import { getChatGPTManifest } from '@embodiment/helpers/chatgpt.helper';
+import { getOpenAPIJSON } from '@embodiment/helpers/openapi-adapter.helper';
+import agentLoader from '@embodiment/middlewares/agentLoader.mw';
+import express from 'express';
const router = express.Router();
-router.get(
- "/.well-known/ai-plugin.json",
- agentLoader,
- async (req: any, res) => {
- let domain = req.hostname;
-
- const manifest = await getChatGPTManifest(req._rawAgent, domain).catch(
- (error) => {
- console.error(error);
- return { error: error.message };
- }
- );
+router.get('/.well-known/ai-plugin.json', agentLoader, async (req: any, res) => {
+ let domain = req.hostname;
- if ("error" in manifest && manifest.error) {
- return res.status(500).send({ error: manifest.error });
- }
+ const manifest = await getChatGPTManifest(req._rawAgent, domain).catch(error => {
+ console.error(error);
+ return { error: error.message };
+ });
- console.log(
- `Manifest requested from domain ${domain} = ` +
- JSON.stringify(manifest, null, 2)
- );
- res.setHeader("Content-Type", "application/json");
- res.send(JSON.stringify(manifest, null, 2));
- //res.json(manifest);
+ if ('error' in manifest && manifest.error) {
+ return res.status(500).send({ error: manifest.error });
}
-);
-router.get("/api-docs/openapi-gpt.json", agentLoader, async (req: any, res) => {
+ console.log(`Manifest requested from domain ${domain} = ` + JSON.stringify(manifest, null, 2));
+ res.setHeader('Content-Type', 'application/json');
+ res.send(JSON.stringify(manifest, null, 2));
+ //res.json(manifest);
+});
+
+router.get('/api-docs/openapi-gpt.json', agentLoader, async (req: any, res) => {
let domain = req.hostname;
- const openAPIObj = await getOpenAPIJSON(
- req._rawAgent,
- domain,
- req._agentVersion,
- true
- ).catch((error) => {
+ const openAPIObj = await getOpenAPIJSON(req._rawAgent, domain, req._agentVersion, true).catch(error => {
console.error(error);
return { error: error.message };
});
@@ -55,22 +41,18 @@ router.get("/api-docs/openapi-gpt.json", agentLoader, async (req: any, res) => {
//console.log(`openAPI requested from domain ${domain} = ` + JSON.stringify(transformedSpec, null, 2));
//FIXME : should use a more robust solution for limiting the function description length
//ChatGPT function description is limited to 300 characters max, but SmythOS are not
- if ("paths" in transformedSpec) {
+ if ('paths' in transformedSpec) {
for (let path in transformedSpec.paths) {
const entry = transformedSpec.paths[path];
for (let method in entry) {
if (!entry[method].summary) continue;
// * Improvement: Instead of truncating the summary, we can rephrase it using an LLM.
- entry[method].summary = splitOnSeparator(
- entry[method].summary,
- 300,
- "."
- );
+ entry[method].summary = splitOnSeparator(entry[method].summary, 300, '.');
}
}
}
//set application type to json
- res.setHeader("Content-Type", "application/json");
+ res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(transformedSpec, null, 2));
});
@@ -96,26 +78,26 @@ function transformOpenAPI301to310(spec: any): any {
const transformed = JSON.parse(JSON.stringify(spec));
// Update version
- transformed.openapi = "3.1.0";
+ transformed.openapi = '3.1.0';
// Transform schemas recursively
function transformSchema(schema: any): any {
- if (!schema || typeof schema !== "object") return schema;
+ if (!schema || typeof schema !== 'object') return schema;
// Handle array schemas - ensure items is properly defined
- if (schema.type === "array") {
+ if (schema.type === 'array') {
if (!schema.items || Object.keys(schema.items).length === 0) {
- schema.items = { type: "string" }; // Default to string items
+ schema.items = { type: 'string' }; // Default to string items
} else {
schema.items = transformSchema(schema.items);
}
}
// Handle object schemas - fix empty additionalProperties
- if (schema.type === "object") {
+ if (schema.type === 'object') {
if (
schema.additionalProperties !== undefined &&
- typeof schema.additionalProperties === "object" &&
+ typeof schema.additionalProperties === 'object' &&
Object.keys(schema.additionalProperties).length === 0
) {
schema.additionalProperties = true; // Allow any additional properties
@@ -130,10 +112,10 @@ function transformOpenAPI301to310(spec: any): any {
}
// Handle binary format - convert to string with contentEncoding
- if (schema.format === "binary") {
+ if (schema.format === 'binary') {
delete schema.format;
- schema.type = "string";
- schema.contentEncoding = "base64";
+ schema.type = 'string';
+ schema.contentEncoding = 'base64';
}
// Handle nullable fields (3.0.1 -> 3.1.0)
@@ -141,9 +123,7 @@ function transformOpenAPI301to310(spec: any): any {
delete schema.nullable;
// Convert to union type with null
if (schema.type) {
- schema.type = Array.isArray(schema.type)
- ? [...schema.type, "null"]
- : [schema.type, "null"];
+ schema.type = Array.isArray(schema.type) ? [...schema.type, 'null'] : [schema.type, 'null'];
}
}
@@ -160,7 +140,7 @@ function transformOpenAPI301to310(spec: any): any {
if (transformed.paths) {
for (const pathItem of Object.values(transformed.paths)) {
for (const operation of Object.values(pathItem as any)) {
- if (typeof operation !== "object" || !operation) continue;
+ if (typeof operation !== 'object' || !operation) continue;
const op = operation as any;
@@ -168,9 +148,7 @@ function transformOpenAPI301to310(spec: any): any {
if (op.requestBody?.content) {
for (const mediaObj of Object.values(op.requestBody.content)) {
if ((mediaObj as any).schema) {
- (mediaObj as any).schema = transformSchema(
- (mediaObj as any).schema
- );
+ (mediaObj as any).schema = transformSchema((mediaObj as any).schema);
}
}
}
@@ -181,9 +159,7 @@ function transformOpenAPI301to310(spec: any): any {
if ((response as any).content) {
for (const mediaObj of Object.values((response as any).content)) {
if ((mediaObj as any).schema) {
- (mediaObj as any).schema = transformSchema(
- (mediaObj as any).schema
- );
+ (mediaObj as any).schema = transformSchema((mediaObj as any).schema);
}
}
}
@@ -205,9 +181,7 @@ function transformOpenAPI301to310(spec: any): any {
// Transform component schemas
if (transformed.components?.schemas) {
- for (const [name, schema] of Object.entries(
- transformed.components.schemas
- )) {
+ for (const [name, schema] of Object.entries(transformed.components.schemas)) {
transformed.components.schemas[name] = transformSchema(schema);
}
}
@@ -215,7 +189,7 @@ function transformOpenAPI301to310(spec: any): any {
return transformed;
}
-function splitOnSeparator(str = "", maxLen: number, separator = " .") {
+function splitOnSeparator(str = '', maxLen: number, separator = ' .') {
if (str.length <= maxLen) {
return str;
}
diff --git a/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts
index 859a6308..e460a986 100644
--- a/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts
@@ -1,17 +1,17 @@
-import axios from "axios";
-import express from "express";
+import axios from 'axios';
+import express from 'express';
-import { AccessCandidate, Agent, BinaryInput } from "@smythos/sre";
+import { AccessCandidate, Agent, BinaryInput } from '@smythos/sre';
-import config from "@core/config";
-import { readAgentOAuthConfig } from "@core/helpers/agent.helper";
-import { uploadHandler } from "@core/middlewares/uploadHandler.mw";
+import config from '@core/config';
+import { readAgentOAuthConfig } from '@core/helpers/agent.helper';
+import { uploadHandler } from '@core/middlewares/uploadHandler.mw';
-import { EMBODIMENT_TYPES } from "@embodiment/constants";
-import { getChatGPTManifest } from "@embodiment/helpers/chatgpt.helper";
-import agentLoader from "@embodiment/middlewares/agentLoader.mw";
-import ChatbotLoader from "@embodiment/middlewares/ChatbotLoader.mw";
-import { buildConversationId } from "@embodiment/utils/chat.utils";
+import { EMBODIMENT_TYPES } from '@embodiment/constants';
+import { getChatGPTManifest } from '@embodiment/helpers/chatgpt.helper';
+import agentLoader from '@embodiment/middlewares/agentLoader.mw';
+import ChatbotLoader from '@embodiment/middlewares/ChatbotLoader.mw';
+import { buildConversationId } from '@embodiment/utils/chat.utils';
// Import ChatbotResponse type for proper typing
type ChatbotResponse = {
@@ -34,7 +34,7 @@ let localAgentAuthorizations = {};
const middleweares = [agentLoader, ChatbotLoader];
router.use(middleweares);
-router.get("/", async (req, res) => {
+router.get('/', async (req, res) => {
const agent: Agent = req._agent;
//FIXME : using name as intro message his as a workaround
const name = agent.name;
@@ -44,28 +44,17 @@ router.get("/", async (req, res) => {
// wait for agent embodiments to be ready
await agent.agentSettings?.embodiments?.ready();
- const chatbotName =
- agent.agentSettings?.embodiments?.get(EMBODIMENT_TYPES.ChatBot, "name") ||
- agent.name;
- let introMessage =
- agent.agentSettings?.embodiments?.get(
- EMBODIMENT_TYPES.ChatBot,
- "introMessage"
- ) || "";
+ const chatbotName = agent.agentSettings?.embodiments?.get(EMBODIMENT_TYPES.ChatBot, 'name') || agent.name;
+ let introMessage = agent.agentSettings?.embodiments?.get(EMBODIMENT_TYPES.ChatBot, 'introMessage') || '';
//escape string for javascript
introMessage = introMessage.replace(/'/g, "\\'").replace(/"/g, '\\"');
- const logo =
- agent.agentSettings?.embodiments?.get(EMBODIMENT_TYPES.ChatBot, "icon") ||
- "https://proxy-02.api.smyth.ai/static/img/icon.svg";
- const colors = agent.agentSettings?.embodiments?.get(
- EMBODIMENT_TYPES.ChatBot,
- "colors"
- );
+ const logo = agent.agentSettings?.embodiments?.get(EMBODIMENT_TYPES.ChatBot, 'icon') || 'https://proxy-02.api.smyth.ai/static/img/icon.svg';
+ const colors = agent.agentSettings?.embodiments?.get(EMBODIMENT_TYPES.ChatBot, 'colors');
const { allowAttachments = true } = req.query;
- let debugScript = "";
+ let debugScript = '';
if (isTestDomain || debugSessionEnabled) {
debugScript = `
<script src="/static/embodiment/chatBot/chatbot-debug.js"></script>
@@ -101,20 +90,17 @@ initDebug('${config.env.UI_SERVER}', '${agent.id}');
</html>`);
});
-router.get("/chat-configs", async (req: any, res) => {
+router.get('/chat-configs', async (req: any, res) => {
if (!req._chatbot) {
- return res.status(404).send({ error: "Chatbot not found" });
+ return res.status(404).send({ error: 'Chatbot not found' });
}
const agent: Agent = req._agent;
- const pluginManifest = await getChatGPTManifest(
- agent.domain,
- agent.version
- ).catch((error) => {
+ const pluginManifest = await getChatGPTManifest(agent.domain, agent.version).catch(error => {
return null;
});
if (!pluginManifest) {
- return res.status(404).send({ error: "Chatbot Config not found" });
+ return res.status(404).send({ error: 'Chatbot Config not found' });
}
if (agent.usingTestDomain) {
@@ -124,9 +110,9 @@ router.get("/chat-configs", async (req: any, res) => {
res.send(chatbot.pluginManifest);
});
-router.post("/chat-stream", async (req, res) => {
+router.post('/chat-stream', async (req, res) => {
let streamStarted = false;
- const isLocalAgent = req.hostname.includes("localagent");
+ const isLocalAgent = req.hostname.includes('localagent');
const agentId = req._agent?.id;
const agentVersion = req._agent?.version;
const isDebugSession = req._agent.debugSessionEnabled;
@@ -144,52 +130,47 @@ router.post("/chat-stream", async (req, res) => {
try {
let { message, attachments = [] } = req.body;
if (attachments.length > 0) {
- message = [
- message,
- "###",
- "Attachments:",
- ...attachments.map((attachment) => `- ${attachment.url}`),
- ].join("\n");
+ message = [message, '###', 'Attachments:', ...attachments.map(attachment => `- ${attachment.url}`)].join('\n');
}
if (!req._chatbot) {
- return res.status(404).send({ error: "Chatbot not found" });
+ return res.status(404).send({ error: 'Chatbot not found' });
}
const chatbot = req._chatbot;
- chatbot.conversationID = req.headers["x-conversation-id"] || req.sessionID;
- const monitorId = req.headers["x-monitor-id"];
+ chatbot.conversationID = req.headers['x-conversation-id'] || req.sessionID;
+ const monitorId = req.headers['x-monitor-id'];
const hasAttachments = attachments?.length > 0;
//TODO @AK : pass agent id and version in order to allow bypassing http call for agent invocation in conv manager
//const headers = { 'X-AGENT-ID': agentId, 'X-AGENT-VERSION': req._agent?.version };
const headers = isDebugSession
? {
- "X-DEBUG": true,
- "X-AGENT-ID": agentId,
- "X-MONITOR-ID": monitorId,
- "X-AGENT-REMOTE-CALL": hasAttachments, // for now, we're assuming that all attachments require injected agent which needs remote call
- "x-conversation-id": chatbot.conversationID,
+ 'X-DEBUG': true,
+ 'X-AGENT-ID': agentId,
+ 'X-MONITOR-ID': monitorId,
+ 'X-AGENT-REMOTE-CALL': hasAttachments, // for now, we're assuming that all attachments require injected agent which needs remote call
+ 'x-conversation-id': chatbot.conversationID,
}
: {
- "X-AGENT-ID": agentId,
- "X-MONITOR-ID": monitorId,
- "X-AGENT-VERSION": agentVersion,
- "X-AGENT-REMOTE-CALL": hasAttachments,
- "x-conversation-id": chatbot.conversationID,
+ 'X-AGENT-ID': agentId,
+ 'X-MONITOR-ID': monitorId,
+ 'X-AGENT-VERSION': agentVersion,
+ 'X-AGENT-REMOTE-CALL': hasAttachments,
+ 'x-conversation-id': chatbot.conversationID,
};
if (verifiedKey) {
- headers["Authorization"] = `Bearer ${verifiedKey}`;
+ headers['Authorization'] = `Bearer ${verifiedKey}`;
}
// Set up an event listener for client disconnection
- req.on("close", () => {
+ req.on('close', () => {
abortController.abort();
});
//set response headers
- res.setHeader("Content-Type", "text/event-stream");
- res.setHeader("Cache-Control", "no-cache");
- res.setHeader("Connection", "keep-alive");
+ res.setHeader('Content-Type', 'text/event-stream');
+ res.setHeader('Cache-Control', 'no-cache');
+ res.setHeader('Connection', 'keep-alive');
await chatbot.getChatStreaming({
message,
@@ -207,9 +188,9 @@ router.post("/chat-stream", async (req, res) => {
console.error(error);
if (!streamStarted) {
res.status(500).send({
- content: error?.message || "An error occurred. Please try again later.",
+ content: error?.message || 'An error occurred. Please try again later.',
isError: true,
- errorType: "api_error",
+ errorType: 'api_error',
});
} else {
// Stream error message in the same format as normal responses
@@ -217,17 +198,17 @@ router.post("/chat-stream", async (req, res) => {
JSON.stringify({
content: "I'm not able to contact the server. Please try again.",
isError: true,
- errorType: "connection_error",
- })
+ errorType: 'connection_error',
+ }),
);
res.end();
}
}
});
-router.get("/params", async (req, res) => {
+router.get('/params', async (req, res) => {
if (!req._chatbot) {
- return res.status(404).send({ error: "Chatbot not found" });
+ return res.status(404).send({ error: 'Chatbot not found' });
}
const agent: Agent = req._agent;
@@ -238,15 +219,12 @@ router.get("/params", async (req, res) => {
// await agent.agentSettings?.ready();
// await agent.agentSettings?.embodiments?.ready();
- let promises = [
- agent.agentSettings?.ready(),
- agent.agentSettings?.embodiments?.ready(),
- ];
+ let promises = [agent.agentSettings?.ready(), agent.agentSettings?.embodiments?.ready()];
let authInfo;
if (!!agent?.data?.auth) {
- const oauthPromise = readAgentOAuthConfig(agent?.data).then((_auth) => {
+ const oauthPromise = readAgentOAuthConfig(agent?.data).then(_auth => {
authInfo = _auth;
});
promises.push(oauthPromise);
@@ -255,9 +233,7 @@ router.get("/params", async (req, res) => {
await Promise.all(promises);
// Determine if the chatbot is enabled
- let isChatbotEnabled =
- agent?.agentSettings?.get(EMBODIMENT_TYPES.ChatBot.toLowerCase()) ===
- "true";
+ let isChatbotEnabled = agent?.agentSettings?.get(EMBODIMENT_TYPES.ChatBot.toLowerCase()) === 'true';
if (agent && agent.usingTestDomain) {
isChatbotEnabled = true; // Chatbot is always enabled on test domain
@@ -271,33 +247,24 @@ router.get("/params", async (req, res) => {
}
// Retrieve chatbot properties
- const chatbotProperties =
- agent.agentSettings?.embodiments?.get(EMBODIMENT_TYPES.ChatBot) || {};
+ const chatbotProperties = agent.agentSettings?.embodiments?.get(EMBODIMENT_TYPES.ChatBot) || {};
// If chatbot properties exist, append the 'chatbotEnabled' flag
if (chatbotProperties) {
- const isLocalAgent = req.hostname.includes("localagent");
+ const isLocalAgent = req.hostname.includes('localagent');
const agentId = agent?.id;
- const chatbotName =
- agent.agentSettings?.embodiments.get(EMBODIMENT_TYPES.ChatBot, "name") ||
- agent.name;
+ const chatbotName = agent.agentSettings?.embodiments.get(EMBODIMENT_TYPES.ChatBot, 'name') || agent.name;
const sessionAuthorized = isLocalAgent
- ? !!localAgentAuthorizations?.[agentId]?.verifiedKey &&
- localAgentAuthorizations?.[agentId]?.authMethod === authInfo?.method
- : !!sessionData?.agentAuthorizations?.[agentId]?.verifiedKey &&
- sessionData?.agentAuthorizations?.[agentId]?.authMethod ===
- authInfo?.method;
-
- const agentUrl = isLocalAgent
- ? `http://${req.hostname}:${config.env.AGENT_DOMAIN_PORT}`
- : `https://${req.hostname}`;
+ ? !!localAgentAuthorizations?.[agentId]?.verifiedKey && localAgentAuthorizations?.[agentId]?.authMethod === authInfo?.method
+ : !!sessionData?.agentAuthorizations?.[agentId]?.verifiedKey && sessionData?.agentAuthorizations?.[agentId]?.authMethod === authInfo?.method;
+
+ const agentUrl = isLocalAgent ? `http://${req.hostname}:${config.env.AGENT_DOMAIN_PORT}` : `https://${req.hostname}`;
const redirectUri = `${agentUrl}/chatbot/callback`;
const authorizationUrl = `${agentUrl}/oauth/authorize?response_type=code&client_id=${authInfo?.provider?.clientID}&redirect_uri=${redirectUri}`;
const isAuthRequired = () => {
- const isAuthDisabled =
- agent?.debugSessionEnabled && agent.usingTestDomain;
+ const isAuthDisabled = agent?.debugSessionEnabled && agent.usingTestDomain;
const hasAuthMethod = !!authInfo?.method;
const isNotAuthorized = !sessionAuthorized;
return !isAuthDisabled && hasAuthMethod && isNotAuthorized;
@@ -315,7 +282,7 @@ router.get("/params", async (req, res) => {
redirectUri: redirectUri,
authorizationUrl: authorizationUrl,
clientID: authInfo?.provider?.clientID,
- redirectInternalEndpoint: "/chatbot/callback",
+ redirectInternalEndpoint: '/chatbot/callback',
},
});
@@ -324,13 +291,11 @@ router.get("/params", async (req, res) => {
//* Note: chatbot conversations are not created in db table, it is just a uid created on the fly
//* On the other hand, Agent Chat conversations are created in db table and can be retrieved from db
- const isTestDomain = req.hostname.includes(
- `.${config.env.DEFAULT_AGENT_DOMAIN}`
- );
+ const isTestDomain = req.hostname.includes(`.${config.env.DEFAULT_AGENT_DOMAIN}`);
const conversationId = buildConversationId(undefined, isTestDomain);
chatbotProperties.headers = {
- "x-conversation-id": conversationId,
+ 'x-conversation-id': conversationId,
};
res.send(chatbotProperties);
@@ -340,15 +305,10 @@ router.get("/params", async (req, res) => {
}
});
-function setSessionToken(
- req: any,
- res: any,
- token: string,
- authMethod: string
-) {
+function setSessionToken(req: any, res: any, token: string, authMethod: string) {
const agentId = req._agent?.id;
if (!agentId) {
- console.error("Agent ID not found in request");
+ console.error('Agent ID not found in request');
return;
}
@@ -359,16 +319,16 @@ function setSessionToken(
verifiedKey: token,
authMethod: authMethod,
};
- req.session.save((err) => {
+ req.session.save(err => {
if (err) {
- console.error("Error saving session:", err);
+ console.error('Error saving session:', err);
}
});
}
function handleLocalAgent(req: any, token: string, authMethod: string) {
const agentId = req._agent?.id;
- if (req._agent?.domain?.includes("localagent")) {
+ if (req._agent?.domain?.includes('localagent')) {
if (!localAgentAuthorizations) {
localAgentAuthorizations = {};
}
@@ -382,11 +342,7 @@ function handleLocalAgent(req: any, token: string, authMethod: string) {
async function handleOAuthCallback(req: any, res: any) {
if (req.query.code) {
const authInfo = await getAuthInfo(req);
- const accessToken = await exchangeCodeForToken(
- req.query.code,
- req._agent?.domain,
- authInfo
- );
+ const accessToken = await exchangeCodeForToken(req.query.code, req._agent?.domain, authInfo);
if (accessToken) {
const token = accessToken.access_token;
setSessionToken(req, res, token, authInfo?.method);
@@ -419,15 +375,9 @@ function sendCloseTabResponse(res: any) {
</html>`);
}
-async function exchangeCodeForToken(
- code: string,
- domain: string,
- authInfo: any
-): Promise<any> {
- const isLocalAgent = domain.includes("localagent");
- const baseUrl = isLocalAgent
- ? `http://${domain}:${config.env.PORT}`
- : `https://${domain}`;
+async function exchangeCodeForToken(code: string, domain: string, authInfo: any): Promise<any> {
+ const isLocalAgent = domain.includes('localagent');
+ const baseUrl = isLocalAgent ? `http://${domain}:${config.env.PORT}` : `https://${domain}`;
const tokenEndpoint = `${baseUrl}/oauth/token`;
const redirectUri = `${baseUrl}/chatbot/callback`;
@@ -435,11 +385,11 @@ async function exchangeCodeForToken(
const clientSecret = authInfo?.provider?.clientSecret;
if (!clientId || !clientSecret) {
- throw new Error("Missing client ID or client secret");
+ throw new Error('Missing client ID or client secret');
}
const params = new URLSearchParams({
- grant_type: "authorization_code",
+ grant_type: 'authorization_code',
code,
redirect_uri: redirectUri,
client_id: clientId,
@@ -450,49 +400,45 @@ async function exchangeCodeForToken(
const response = await axios.post(tokenEndpoint, params);
return response.data;
} catch (error) {
- console.error("Error exchanging code for token:", error);
+ console.error('Error exchanging code for token:', error);
throw error;
}
}
-router.post("/verify-chat-key", async (req: any, res) => {
+router.post('/verify-chat-key', async (req: any, res) => {
if (!req._chatbot) {
- return res.status(404).json({ error: "Chatbot not found" });
+ return res.status(404).json({ error: 'Chatbot not found' });
}
const { apiKey } = req.body;
const agent: Agent = req._agent;
try {
- const authInfo = agent?.data?.auth
- ? await readAgentOAuthConfig(agent.data)
- : null;
+ const authInfo = agent?.data?.auth ? await readAgentOAuthConfig(agent.data) : null;
if (apiKey !== authInfo?.provider?.token) {
- return res.status(401).json({ error: "Invalid API key", success: false });
+ return res.status(401).json({ error: 'Invalid API key', success: false });
}
setSessionToken(req, res, apiKey, authInfo?.method);
handleLocalAgent(req, apiKey, authInfo?.method);
- return res.json({ message: "Access granted", success: true });
+ return res.json({ message: 'Access granted', success: true });
} catch (error) {
- console.error("Error verifying chat key:", error);
- return res
- .status(500)
- .json({ error: "Internal server error", success: false });
+ console.error('Error verifying chat key:', error);
+ return res.status(500).json({ error: 'Internal server error', success: false });
}
});
-router.get("/callback", async (req: any, res) => {
+router.get('/callback', async (req: any, res) => {
await handleOAuthCallback(req, res);
sendCloseTabResponse(res);
});
-router.post("/upload", uploadHandler, async (req: any, res) => {
+router.post('/upload', uploadHandler, async (req: any, res) => {
try {
if (!req.files || req.files.length === 0) {
- return res.status(400).json({ error: "No files uploaded" });
+ return res.status(400).json({ error: 'No files uploaded' });
}
const agent = req._agent;
@@ -501,18 +447,10 @@ router.post("/upload", uploadHandler, async (req: any, res) => {
for (const file of req.files) {
try {
const candidate = AccessCandidate.agent(agent.id);
- const binaryInput = BinaryInput.from(
- file.buffer,
- null,
- file.mimetype,
- candidate
- );
+ const binaryInput = BinaryInput.from(file.buffer, null, file.mimetype, candidate);
await binaryInput.ready();
// getJsonData implicitly uploads the file to SmythFS
- const fileData = await binaryInput.getJsonData(
- candidate,
- MAX_TTL_CHATBOT_FILE_UPLOAD
- );
+ const fileData = await binaryInput.getJsonData(candidate, MAX_TTL_CHATBOT_FILE_UPLOAD);
uploadedFiles.push({
size: file.size,
@@ -521,7 +459,7 @@ router.post("/upload", uploadHandler, async (req: any, res) => {
originalName: file.originalname,
});
} catch (error) {
- console.error("Error uploading file:", file.originalname, error);
+ console.error('Error uploading file:', file.originalname, error);
}
}
@@ -530,10 +468,10 @@ router.post("/upload", uploadHandler, async (req: any, res) => {
files: uploadedFiles,
});
} catch (error) {
- console.error("Error handling file upload:", error);
+ console.error('Error handling file upload:', error);
res.status(500).json({
success: false,
- error: "Failed to process file upload",
+ error: 'Failed to process file upload',
});
}
});
diff --git a/packages/runtime/src/modules/embodiment/modules/formPreview/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/formPreview/routes/router.ts
index f6792626..e787621e 100644
--- a/packages/runtime/src/modules/embodiment/modules/formPreview/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/formPreview/routes/router.ts
@@ -1,15 +1,15 @@
-import config from "@core/config";
-import { callSkill } from "@embodiment/helpers/formPreview.helper";
-import agentLoader from "@embodiment/middlewares/agentLoader.mw";
-import { Agent } from "@smythos/sre";
-import express from "express";
+import config from '@core/config';
+import { callSkill } from '@embodiment/helpers/formPreview.helper';
+import agentLoader from '@embodiment/middlewares/agentLoader.mw';
+import { Agent } from '@smythos/sre';
+import express from 'express';
const router = express.Router();
const middlewares = [agentLoader];
router.use(middlewares);
-router.get("/", async (req, res) => {
+router.get('/', async (req, res) => {
const agent: Agent = req._agent;
res.send(`
@@ -34,14 +34,14 @@ router.get("/", async (req, res) => {
</html>`);
});
-router.get("/params", async (req, res) => {
+router.get('/params', async (req, res) => {
const agent: Agent = req._agent;
let promises = [agent.agentSettings?.ready()];
await Promise.all(promises);
- const isLocalAgent = req.hostname.includes("localagent");
+ const isLocalAgent = req.hostname.includes('localagent');
const agentId = agent?.id;
const port = isLocalAgent ? config.env.AGENT_DOMAIN_PORT : undefined;
@@ -56,18 +56,16 @@ router.get("/params", async (req, res) => {
res.send(agentData);
});
-router.post("/call-skill", async (req, res) => {
+router.post('/call-skill', async (req, res) => {
const agent: Agent = req._agent;
const agentId = agent?.id;
const { componentId, payload, version } = req.body;
- const component = (agent.data as Agent).components.find(
- (c) => c.id === componentId
- );
+ const component = (agent.data as Agent).components.find(c => c.id === componentId);
if (!component) {
- res.status(404).send({ error: "Component not found" });
+ res.status(404).send({ error: 'Component not found' });
}
const response = await callSkill({
@@ -75,7 +73,7 @@ router.post("/call-skill", async (req, res) => {
body: {
componentId: componentId as string,
payload: payload as Record<string, any>,
- version: version as "dev" | "latest",
+ version: version as 'dev' | 'latest',
},
endpoint: component.data.endpoint!,
});
diff --git a/packages/runtime/src/modules/embodiment/modules/mcp/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/mcp/routes/router.ts
index 9b30a1c9..34d025fd 100644
--- a/packages/runtime/src/modules/embodiment/modules/mcp/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/mcp/routes/router.ts
@@ -1,49 +1,31 @@
-import express from "express";
-import agentLoader from "@embodiment/middlewares/agentLoader.mw";
-import { Agent } from "@smythos/sre";
-import { getOpenAPIJSON } from "@embodiment/helpers/openapi-adapter.helper";
-import { Server } from "@modelcontextprotocol/sdk/server/index.js";
-import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
-import {
- CallToolRequestSchema,
- ListToolsRequestSchema,
- Tool,
-} from "@modelcontextprotocol/sdk/types.js";
-import { AgentProcess } from "@smythos/sre";
-import {
- extractMCPToolSchema,
- formatMCPSchemaProperties,
- isMcpEnabled,
-} from "../services/mcp.services";
+import express from 'express';
+import agentLoader from '@embodiment/middlewares/agentLoader.mw';
+import { Agent } from '@smythos/sre';
+import { getOpenAPIJSON } from '@embodiment/helpers/openapi-adapter.helper';
+import { Server } from '@modelcontextprotocol/sdk/server/index.js';
+import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
+import { CallToolRequestSchema, ListToolsRequestSchema, Tool } from '@modelcontextprotocol/sdk/types.js';
+import { AgentProcess } from '@smythos/sre';
+import { extractMCPToolSchema, formatMCPSchemaProperties, isMcpEnabled } from '../services/mcp.services';
const router = express.Router();
//let transport: SSEServerTransport;
-const clientTransports = new Map<
- string,
- { transport: SSEServerTransport; server: Server }
->();
+const clientTransports = new Map<string, { transport: SSEServerTransport; server: Server }>();
-router.get("/sse", agentLoader, async (req: any, res) => {
+router.get('/sse', agentLoader, async (req: any, res) => {
try {
const agent: Agent = req._agent;
- if (agent?.data?.auth?.method && agent?.data?.auth?.method !== "none") {
+ if (agent?.data?.auth?.method && agent?.data?.auth?.method !== 'none') {
return res.status(400).send({
- error: "Agents with authentication enabled are not supported for MCP",
+ error: 'Agents with authentication enabled are not supported for MCP',
});
}
await agent.agentSettings?.ready();
const isEnabled = isMcpEnabled(agent);
if (!isEnabled) {
- return res
- .status(503)
- .send({ error: "MCP is not enabled for this agent" });
+ return res.status(503).send({ error: 'MCP is not enabled for this agent' });
}
- const openAPISpec = await getOpenAPIJSON(
- agent,
- "localhost",
- "latest",
- true
- );
+ const openAPISpec = await getOpenAPIJSON(agent, 'localhost', 'latest', true);
// Server implementation
const server = new Server(
@@ -55,81 +37,74 @@ router.get("/sse", agentLoader, async (req: any, res) => {
capabilities: {
tools: {},
},
- }
+ },
);
- req.on("error", (error: any) => {
- console.error("Error:", error);
+ req.on('error', (error: any) => {
+ console.error('Error:', error);
// server.close();
});
// Handle client disconnect
- req.on("close", () => {
- console.log("Client disconnected");
+ req.on('close', () => {
+ console.log('Client disconnected');
clientTransports.delete(transport.sessionId);
// server.close();
});
server.onerror = (error: any) => {
- console.error("Server error:", error);
+ console.error('Server error:', error);
// server.close();
};
server.onclose = async () => {
- console.log("Server closing");
+ console.log('Server closing');
// await server.close();
// process.exit(0);
};
// Extract available endpoints and their methods
- const tools: Tool[] = Object.entries(openAPISpec.paths).map(
- ([path, methods]) => {
- const method = Object.keys(methods)[0];
- const endpoint = path.split("/api/")[1];
- const operation = methods[method];
- const schema = extractMCPToolSchema(operation, method);
- const properties = formatMCPSchemaProperties(schema);
-
- return {
- name: endpoint,
- description:
- operation.summary ||
- `Endpoint that handles ${method.toUpperCase()} requests to ${endpoint}. ` +
- `${schema?.description || ""}`,
- inputSchema: {
- type: "object",
- properties: properties,
- required: schema?.required || [],
- },
- };
- }
- );
+ const tools: Tool[] = Object.entries(openAPISpec.paths).map(([path, methods]) => {
+ const method = Object.keys(methods)[0];
+ const endpoint = path.split('/api/')[1];
+ const operation = methods[method];
+ const schema = extractMCPToolSchema(operation, method);
+ const properties = formatMCPSchemaProperties(schema);
+
+ return {
+ name: endpoint,
+ description: operation.summary || `Endpoint that handles ${method.toUpperCase()} requests to ${endpoint}. ` + `${schema?.description || ''}`,
+ inputSchema: {
+ type: 'object',
+ properties: properties,
+ required: schema?.required || [],
+ },
+ };
+ });
// Tool handlers
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools,
}));
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
+ server.setRequestHandler(CallToolRequestSchema, async request => {
try {
const { name, arguments: args } = request.params;
if (!args) {
- throw new Error("No arguments provided");
+ throw new Error('No arguments provided');
}
// Find the matching tool from our tools array
- const tool = tools.find((t) => t.name === name);
+ const tool = tools.find(t => t.name === name);
if (!tool) {
return {
- content: [{ type: "text", text: `Unknown tool: ${name}` }],
+ content: [{ type: 'text', text: `Unknown tool: ${name}` }],
isError: true,
};
}
try {
// Extract method and path from OpenAPI spec
- const pathEntry = Object.entries(openAPISpec.paths).find(
- ([path]) => path.split("/api/")[1] === name
- );
+ const pathEntry = Object.entries(openAPISpec.paths).find(([path]) => path.split('/api/')[1] === name);
if (!pathEntry) {
throw new Error(`Could not find path for tool: ${name}`);
}
@@ -145,14 +120,14 @@ router.get("/sse", agentLoader, async (req: any, res) => {
});
return {
- content: [{ type: "text", text: JSON.stringify(result) }],
+ content: [{ type: 'text', text: JSON.stringify(result) }],
isError: false,
};
} catch (error) {
return {
content: [
{
- type: "text",
+ type: 'text',
text: `Error processing request: ${error.message}`,
},
],
@@ -163,10 +138,8 @@ router.get("/sse", agentLoader, async (req: any, res) => {
return {
content: [
{
- type: "text",
- text: `Error: ${
- error instanceof Error ? error.message : String(error)
- }`,
+ type: 'text',
+ text: `Error: ${error instanceof Error ? error.message : String(error)}`,
},
],
isError: true,
@@ -174,24 +147,24 @@ router.get("/sse", agentLoader, async (req: any, res) => {
}
});
- const transport = new SSEServerTransport("/emb/mcp/message", res);
+ const transport = new SSEServerTransport('/emb/mcp/message', res);
await server.connect(transport);
clientTransports.set(transport.sessionId, { transport, server });
- console.log("Generated sessionId", transport.sessionId);
- console.log("MCP Server running on sse");
+ console.log('Generated sessionId', transport.sessionId);
+ console.log('MCP Server running on sse');
} catch (error: any) {
console.error(error);
return res.status(500).send({ error: error.message });
}
});
-router.post("/message", async (req, res) => {
+router.post('/message', async (req, res) => {
const sessionId = req.query.sessionId;
- console.log("Received sessionId", sessionId);
+ console.log('Received sessionId', sessionId);
const transport = clientTransports.get(sessionId as string)?.transport;
if (!transport) {
- return res.status(404).send({ error: "Transport not found" });
+ return res.status(404).send({ error: 'Transport not found' });
}
await transport.handlePostMessage(req, res, req.body);
});
diff --git a/packages/runtime/src/modules/embodiment/modules/mcp/services/mcp.services.ts b/packages/runtime/src/modules/embodiment/modules/mcp/services/mcp.services.ts
index acac4552..efd2161c 100644
--- a/packages/runtime/src/modules/embodiment/modules/mcp/services/mcp.services.ts
+++ b/packages/runtime/src/modules/embodiment/modules/mcp/services/mcp.services.ts
@@ -1,5 +1,5 @@
-import { Agent } from "@smythos/sre";
-const MCP_SETTINGS_KEY = "mcp";
+import { Agent } from '@smythos/sre';
+const MCP_SETTINGS_KEY = 'mcp';
export const isMcpEnabled = (agent: Agent) => {
if (agent.usingTestDomain) {
@@ -21,15 +21,15 @@ export const isMcpEnabled = (agent: Agent) => {
};
export function extractMCPToolSchema(jsonSpec: any, method: string) {
- if (method.toLowerCase() === "get") {
+ if (method.toLowerCase() === 'get') {
const schema = jsonSpec?.parameters;
if (!schema) return {};
const properties = {};
const required = [];
- schema.forEach((param) => {
- if (param.in === "query") {
+ schema.forEach(param => {
+ if (param.in === 'query') {
properties[param.name] = param.schema;
if (param.required) {
required.push(param.name);
@@ -38,12 +38,12 @@ export function extractMCPToolSchema(jsonSpec: any, method: string) {
});
return {
- type: "object",
+ type: 'object',
properties,
required,
};
}
- const schema = jsonSpec?.requestBody?.content?.["application/json"]?.schema;
+ const schema = jsonSpec?.requestBody?.content?.['application/json']?.schema;
return schema;
}
@@ -52,11 +52,11 @@ export function formatMCPSchemaProperties(schema: any) {
for (const property in properties) {
const propertySchema = properties[property];
- if (propertySchema.type === "array") {
+ if (propertySchema.type === 'array') {
properties[property] = {
- type: "array",
+ type: 'array',
items: {
- type: ["string", "number", "boolean", "object", "array"],
+ type: ['string', 'number', 'boolean', 'object', 'array'],
},
};
}
diff --git a/packages/runtime/src/modules/embodiment/modules/openai/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/openai/routes/router.ts
index de48824d..88adc3fb 100644
--- a/packages/runtime/src/modules/embodiment/modules/openai/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/openai/routes/router.ts
@@ -1,19 +1,16 @@
-import {
- DEFAULT_AGENT_MODEL_SETTINGS_KEY,
- DEFAULT_MODEL,
-} from "@core/constants";
-import { validate } from "@core/middlewares/validate.mw";
-import { extractBearerToken } from "@core/services/smythAPIReq";
-import ApiError from "@core/utils/apiError";
-import agentLoader from "@embodiment/middlewares/agentLoader.mw";
-import { chatService } from "@embodiment/modules/openai/services/chat.service";
-import { chatValidations } from "@embodiment/modules/openai/validations/openai.validation";
-import { Logger } from "@smythos/sre";
-import { Request, Response, Router } from "express";
-import OpenAI from "openai";
-import { Readable } from "stream";
+import { DEFAULT_AGENT_MODEL_SETTINGS_KEY, DEFAULT_MODEL } from '@core/constants';
+import { validate } from '@core/middlewares/validate.mw';
+import { extractBearerToken } from '@core/services/smythAPIReq';
+import ApiError from '@core/utils/apiError';
+import agentLoader from '@embodiment/middlewares/agentLoader.mw';
+import { chatService } from '@embodiment/modules/openai/services/chat.service';
+import { chatValidations } from '@embodiment/modules/openai/validations/openai.validation';
+import { Logger } from '@smythos/sre';
+import { Request, Response, Router } from 'express';
+import OpenAI from 'openai';
+import { Readable } from 'stream';
const router = Router();
-const console = Logger("[Embodiment] Router: OpenAI");
+const console = Logger('[Embodiment] Router: OpenAI');
// Helper function to create OpenAI API errors
const createOpenAIError = (statusCode: number, error: any) => {
@@ -25,70 +22,63 @@ const createOpenAIError = (statusCode: number, error: any) => {
type: error?.name,
},
error?.message,
- null
+ null,
);
};
-router.post(
- "/v1/chat/completions",
- agentLoader,
- validate(chatValidations.chatCompletion),
- async (req: Request & { _agent: any }, res: Response) => {
- try {
- const agent = req._agent;
+router.post('/v1/chat/completions', agentLoader, validate(chatValidations.chatCompletion), async (req: Request & { _agent: any }, res: Response) => {
+ try {
+ const agent = req._agent;
- // wait for agent settings to be ready
- await agent.agentSettings?.ready();
+ // wait for agent settings to be ready
+ await agent.agentSettings?.ready();
- const model =
- agent.agentSettings?.get(DEFAULT_AGENT_MODEL_SETTINGS_KEY) ||
- DEFAULT_MODEL;
+ const model = agent.agentSettings?.get(DEFAULT_AGENT_MODEL_SETTINGS_KEY) || DEFAULT_MODEL;
- const authHeader = req.headers["authorization"];
- const apiKey = extractBearerToken(authHeader);
+ const authHeader = req.headers['authorization'];
+ const apiKey = extractBearerToken(authHeader);
- const result = await chatService.chatCompletion({
- apiKey,
- modelId: model,
- params: req.body,
- options: req.query,
- agent,
- });
-
- if (result instanceof ApiError) {
- const error = createOpenAIError(result.statusCode, result);
- return res.status(result.statusCode).json(error);
- }
+ const result = await chatService.chatCompletion({
+ apiKey,
+ modelId: model,
+ params: req.body,
+ options: req.query,
+ agent,
+ });
- if (result instanceof Readable) {
- // Set proper headers for SSE
- res.setHeader("Content-Type", "text/event-stream");
- res.setHeader("Cache-Control", "no-cache");
- res.setHeader("Connection", "keep-alive");
+ if (result instanceof ApiError) {
+ const error = createOpenAIError(result.statusCode, result);
+ return res.status(result.statusCode).json(error);
+ }
- let headersSent = false;
+ if (result instanceof Readable) {
+ // Set proper headers for SSE
+ res.setHeader('Content-Type', 'text/event-stream');
+ res.setHeader('Cache-Control', 'no-cache');
+ res.setHeader('Connection', 'keep-alive');
- result.on("error", (error: any) => {
- console.warn("Chat completion error:", error);
+ let headersSent = false;
- const status = error?.status || 500;
+ result.on('error', (error: any) => {
+ console.warn('Chat completion error:', error);
- const apiError = createOpenAIError(status, error);
- res.status(status).json(apiError);
- });
+ const status = error?.status || 500;
- result.pipe(res);
- } else {
- res.json(result);
- }
- } catch (error) {
- console.warn("Chat completion error:", error);
+ const apiError = createOpenAIError(status, error);
+ res.status(status).json(apiError);
+ });
- const status = error?.status || 500;
- const apiError = createOpenAIError(status, error);
- return res.status(status).json(apiError);
+ result.pipe(res);
+ } else {
+ res.json(result);
}
+ } catch (error) {
+ console.warn('Chat completion error:', error);
+
+ const status = error?.status || 500;
+ const apiError = createOpenAIError(status, error);
+ return res.status(status).json(apiError);
}
-);
+});
export { router as openaiRouter };
diff --git a/packages/runtime/src/modules/embodiment/modules/openai/services/chat.service.ts b/packages/runtime/src/modules/embodiment/modules/openai/services/chat.service.ts
index 2141a0c8..15db3553 100644
--- a/packages/runtime/src/modules/embodiment/modules/openai/services/chat.service.ts
+++ b/packages/runtime/src/modules/embodiment/modules/openai/services/chat.service.ts
@@ -1,19 +1,13 @@
-import crypto from "crypto";
-import { OpenAI } from "openai";
-import { Readable } from "stream";
+import crypto from 'crypto';
+import { OpenAI } from 'openai';
+import { Readable } from 'stream';
-import {
- AccessCandidate,
- Agent,
- ConnectorService,
- Conversation,
- Logger,
-} from "@smythos/sre";
+import { AccessCandidate, Agent, ConnectorService, Conversation, Logger } from '@smythos/sre';
-import ApiError from "@core/utils/apiError";
-import { getAgentIdAndVersion } from "@core/helpers/agent.helper";
+import ApiError from '@core/utils/apiError';
+import { getAgentIdAndVersion } from '@core/helpers/agent.helper';
-const console = Logger("[Embodiment] Service: OpenAI Chat");
+const console = Logger('[Embodiment] Service: OpenAI Chat');
interface ChatCompletionParams {
apiKey: string;
@@ -32,14 +26,12 @@ class OpenAIChatService {
params,
options,
agent,
- }: ChatCompletionParams): Promise<
- OpenAI.Chat.Completions.ChatCompletion | Readable | ApiError
- > {
+ }: ChatCompletionParams): Promise<OpenAI.Chat.Completions.ChatCompletion | Readable | ApiError> {
const { agentId, agentVersion } = getAgentIdAndVersion(params.model);
- console.log("parsed agentId and agentVersion", agentId, agentVersion);
+ console.log('parsed agentId and agentVersion', agentId, agentVersion);
if (!apiKey) {
- return new ApiError(401, "Invalid Authentication", "Unauthorized");
+ return new ApiError(401, 'Invalid Authentication', 'Unauthorized');
}
// TODO: move this to the agent loader middleware
@@ -48,19 +40,19 @@ class OpenAIChatService {
const exists = await vaultConnector
.user(accessCandidate)
.exists(apiKey)
- .catch((error) => {
- console.error("Error checking if api key exists:", error);
+ .catch(error => {
+ console.error('Error checking if api key exists:', error);
return false;
});
if (!exists) {
- return new ApiError(401, "Incorrect API key provided", "Unauthorized");
+ return new ApiError(401, 'Incorrect API key provided', 'Unauthorized');
}
const systemPrompt = params.messages
- .filter((m) => m.role === "system")
- .map((m) => m.content)
- .join("\n");
+ .filter(m => m.role === 'system')
+ .map(m => m.content)
+ .join('\n');
// Adapt the model based on the user's plan, especially to support certain OpenAI models for legacy users with limited tokens without their own API key.
const conv = new Conversation(modelId, agentId, { agentVersion });
@@ -69,21 +61,18 @@ class OpenAIChatService {
conv.systemPrompt += `\n\n######\n\n${systemPrompt}`;
}
- const history = params.messages.filter((m) => m.role !== "system");
- const lastUserMessageIndx =
- history.length -
- 1 -
- [...history].reverse().findIndex((m) => m.role === "user");
+ const history = params.messages.filter(m => m.role !== 'system');
+ const lastUserMessageIndx = history.length - 1 - [...history].reverse().findIndex(m => m.role === 'user');
// remove the last user message from the history
const lastUserMessage = history.splice(lastUserMessageIndx, 1)[0];
for (const message of history) {
switch (message.role) {
- case "user":
+ case 'user':
const id = crypto.randomUUID();
conv.context.addUserMessage(message.content as string, id);
break;
- case "assistant":
+ case 'assistant':
const id2 = crypto.randomUUID();
conv.context.addAssistantMessage(message.content as string, id2);
break;
@@ -97,11 +86,11 @@ class OpenAIChatService {
read() {},
});
- conv.on("content", (content) => {
+ conv.on('content', content => {
const now = Date.now();
const preparedContent: OpenAI.Chat.Completions.ChatCompletionChunk = {
id: completionId,
- object: "chat.completion.chunk",
+ object: 'chat.completion.chunk',
created: now,
model: params.model,
choices: [{ index: 0, delta: { content }, finish_reason: null }],
@@ -124,9 +113,9 @@ class OpenAIChatService {
// readable.push(`data: ${JSON.stringify(preparedContent)}\n\n`);
// });
- conv.on("beforeToolCall", (info) => {
+ conv.on('beforeToolCall', info => {
const now = Date.now();
- console.log("Before Tool Call:", info);
+ console.log('Before Tool Call:', info);
// tool name info?.tool?.name
if (!options?.include_status) return;
@@ -138,7 +127,7 @@ class OpenAIChatService {
}[];
} = {
id: completionId,
- object: "chat.completion.chunk",
+ object: 'chat.completion.chunk',
created: now,
model: params.model,
choices: [
@@ -146,7 +135,7 @@ class OpenAIChatService {
finish_reason: null,
index: 0,
delta: {
- content: "",
+ content: '',
status: info?.tool?.name,
},
},
@@ -155,9 +144,9 @@ class OpenAIChatService {
readable.push(`data: ${JSON.stringify(toolStatusChunk)}\n\n`);
});
- conv.on("toolCall", (info) => {
+ conv.on('toolCall', info => {
const now = Date.now();
- console.debug("Tool Call:", info);
+ console.debug('Tool Call:', info);
const toolStatusChunk: OpenAI.Chat.Completions.ChatCompletionChunk & {
choices: {
index: number;
@@ -166,7 +155,7 @@ class OpenAIChatService {
}[];
} = {
id: completionId,
- object: "chat.completion.chunk",
+ object: 'chat.completion.chunk',
created: now,
model: params.model,
choices: [
@@ -175,10 +164,10 @@ class OpenAIChatService {
index: 0,
delta: {
smyth_event: {
- type: "toolCall",
+ type: 'toolCall',
content: info?.tool?.name,
},
- content: "",
+ content: '',
},
},
],
@@ -186,9 +175,9 @@ class OpenAIChatService {
readable.push(`data: ${JSON.stringify(toolStatusChunk)}\n\n`);
});
- conv.on("usage", (usage) => {
+ conv.on('usage', usage => {
const now = Date.now();
- console.debug("Usage:", usage);
+ console.debug('Usage:', usage);
// tool name info?.tool?.name
// if (!options?.include_status) return;
@@ -200,7 +189,7 @@ class OpenAIChatService {
}[];
} = {
id: completionId,
- object: "chat.completion.chunk",
+ object: 'chat.completion.chunk',
created: now,
model: params.model,
choices: [
@@ -209,10 +198,10 @@ class OpenAIChatService {
index: 0,
delta: {
smyth_event: {
- type: "usage",
+ type: 'usage',
content: usage,
},
- content: "",
+ content: '',
},
},
],
@@ -220,43 +209,43 @@ class OpenAIChatService {
readable.push(`data: ${JSON.stringify(toolStatusChunk)}\n\n`);
});
- conv.on("end", () => {
- console.log("streaming: [DONE]");
- readable.push("data: [DONE]\n\n");
+ conv.on('end', () => {
+ console.log('streaming: [DONE]');
+ readable.push('data: [DONE]\n\n');
readable.push(null);
});
- conv.on("error", (error) => {
- console.info("streaming: error", error);
- readable.emit("error", error);
+ conv.on('error', error => {
+ console.info('streaming: error', error);
+ readable.emit('error', error);
});
conv
.streamPrompt(lastUserMessage?.content as string, {
- "X-AGENT-ID": agentId,
+ 'X-AGENT-ID': agentId,
})
- .catch((error) => {
- readable.emit("error", error);
+ .catch(error => {
+ readable.emit('error', error);
});
return readable;
} else {
const now = Date.now();
const result = (await conv.prompt(lastUserMessage?.content as string, {
- "X-AGENT-ID": agentId,
+ 'X-AGENT-ID': agentId,
})) as string;
return {
id: completionId,
- object: "chat.completion",
+ object: 'chat.completion',
created: now,
model: params.model,
choices: [
{
index: 0,
- message: { role: "assistant", content: result, refusal: null },
+ message: { role: 'assistant', content: result, refusal: null },
logprobs: null,
- finish_reason: "stop",
+ finish_reason: 'stop',
},
],
};
@@ -268,14 +257,14 @@ class OpenAIChatService {
readable: Readable,
completionId: string,
now: number,
- params: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming
+ params: OpenAI.Chat.Completions.ChatCompletionCreateParamsNonStreaming,
) {
const shouldEmitStatus = this.firstTime || Math.random() < 0.5;
this.firstTime && (this.firstTime = false);
const randomToolStatus = [
- { text: "Thinking", pauseDelay: 5_000 },
- { text: "Analyzing", pauseDelay: 5_000 },
+ { text: 'Thinking', pauseDelay: 5_000 },
+ { text: 'Analyzing', pauseDelay: 5_000 },
];
if (shouldEmitStatus) {
const status = randomToolStatus.pop();
@@ -288,13 +277,13 @@ class OpenAIChatService {
}[];
} = {
id: completionId,
- object: "chat.completion.chunk",
+ object: 'chat.completion.chunk',
created: now,
model: params.model,
choices: [
{
index: 0,
- delta: { content: "", status: status.text },
+ delta: { content: '', status: status.text },
finish_reason: null,
},
],
diff --git a/packages/runtime/src/modules/embodiment/modules/openai/validations/openai.validation.ts b/packages/runtime/src/modules/embodiment/modules/openai/validations/openai.validation.ts
index d99f5859..8517e139 100644
--- a/packages/runtime/src/modules/embodiment/modules/openai/validations/openai.validation.ts
+++ b/packages/runtime/src/modules/embodiment/modules/openai/validations/openai.validation.ts
@@ -1,24 +1,24 @@
import Joi from 'joi';
export const chatValidations = {
- chatCompletion: {
- headers: Joi.object({
- authorization: Joi.string().required()
- }).required(),
- query: Joi.object({
- include_status: Joi.boolean().optional(),
- }),
- body: Joi.object({
- messages: Joi.array()
- .items(
- Joi.object({
- role: Joi.string().valid('system', 'user', 'assistant').required(),
- content: Joi.string().allow(null).required(),
- })
- )
- .required(),
- model: Joi.string().required(),
- stream: Joi.boolean().optional(),
- }).required(),
- },
+ chatCompletion: {
+ headers: Joi.object({
+ authorization: Joi.string().required(),
+ }).required(),
+ query: Joi.object({
+ include_status: Joi.boolean().optional(),
+ }),
+ body: Joi.object({
+ messages: Joi.array()
+ .items(
+ Joi.object({
+ role: Joi.string().valid('system', 'user', 'assistant').required(),
+ content: Joi.string().allow(null).required(),
+ }),
+ )
+ .required(),
+ model: Joi.string().required(),
+ stream: Joi.boolean().optional(),
+ }).required(),
+ },
};
diff --git a/packages/runtime/src/modules/embodiment/modules/postman/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/postman/routes/router.ts
index b60a0b2d..014a0ce0 100644
--- a/packages/runtime/src/modules/embodiment/modules/postman/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/postman/routes/router.ts
@@ -1,20 +1,15 @@
-import { getOpenAPIJSON } from "@embodiment/helpers/openapi-adapter.helper";
-import agentLoader from "@embodiment/middlewares/agentLoader.mw";
-import express from "express";
-import Converter from "openapi-to-postmanv2";
+import { getOpenAPIJSON } from '@embodiment/helpers/openapi-adapter.helper';
+import agentLoader from '@embodiment/middlewares/agentLoader.mw';
+import express from 'express';
+import Converter from 'openapi-to-postmanv2';
const router = express.Router();
-router.get("/", agentLoader, async (req: any, res) => {
+router.get('/', agentLoader, async (req: any, res) => {
let domain = req.hostname;
try {
- const openAPISpec = await getOpenAPIJSON(
- req._rawAgent,
- domain,
- req._agentVersion,
- false
- ).catch((error) => {
+ const openAPISpec = await getOpenAPIJSON(req._rawAgent, domain, req._agentVersion, false).catch(error => {
console.error(error);
return { error: error.message };
});
@@ -24,25 +19,21 @@ router.get("/", agentLoader, async (req: any, res) => {
}
const conversionResult: any = await new Promise((resolve, reject) => {
- Converter.convert(
- { type: "json", data: openAPISpec },
- {},
- (err, result) => {
- if (err) {
- reject(err);
- } else if (result.result) {
- resolve(result);
- } else {
- reject(new Error(`Conversion failed: ${result.reason}`));
- }
+ Converter.convert({ type: 'json', data: openAPISpec }, {}, (err, result) => {
+ if (err) {
+ reject(err);
+ } else if (result.result) {
+ resolve(result);
+ } else {
+ reject(new Error(`Conversion failed: ${result.reason}`));
}
- );
+ });
});
// Force download the generated Postman collection
const filename = `${req._rawAgent.name}.postman.json`; // Specify the filename here
- res.setHeader("Content-Disposition", `attachment; filename="${filename}"`);
- res.setHeader("Content-Type", "application/json");
+ res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
+ res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(conversionResult?.output?.[0]?.data, null, 2));
} catch (error: any) {
console.error(error);
diff --git a/packages/runtime/src/modules/embodiment/modules/swagger/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/swagger/routes/router.ts
index 7da36bf4..460541f9 100644
--- a/packages/runtime/src/modules/embodiment/modules/swagger/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/swagger/routes/router.ts
@@ -1,16 +1,16 @@
-import express from "express";
-import swaggerUi from "swagger-ui-express";
+import express from 'express';
+import swaggerUi from 'swagger-ui-express';
-import config from "@core/config";
-import { getOpenAPIJSON } from "@embodiment/helpers/openapi-adapter.helper";
-import agentLoader from "@embodiment/middlewares/agentLoader.mw";
-import { Agent } from "@smythos/sre";
+import config from '@core/config';
+import { getOpenAPIJSON } from '@embodiment/helpers/openapi-adapter.helper';
+import agentLoader from '@embodiment/middlewares/agentLoader.mw';
+import { Agent } from '@smythos/sre';
const router = express.Router();
// router.use(swaggerUi.serve);
-router.use("/", agentLoader, async (req: any, res) => {
+router.use('/', agentLoader, async (req: any, res) => {
//TODO : handle release switch : dev, prod, prod old versions [DONE]
const agent: Agent = req._agent;
let domain = req.hostname;
@@ -18,21 +18,16 @@ router.use("/", agentLoader, async (req: any, res) => {
const isTestDomain = agent.usingTestDomain;
// FIXME : use the right version depending on domain [FIXED]
// const version = isTestDomain ? '' : 'latest';
- const openApiDocument = await getOpenAPIJSON(
- req._rawAgent,
- domain,
- req._agentVersion,
- false
- );
-
- if (agent?.data?.auth?.method && agent?.data?.auth?.method != "none") {
+ const openApiDocument = await getOpenAPIJSON(req._rawAgent, domain, req._agentVersion, false);
+
+ if (agent?.data?.auth?.method && agent?.data?.auth?.method != 'none') {
// Add or update security definitions
openApiDocument.components = openApiDocument.components || {};
openApiDocument.components.securitySchemes = {
ApiKeyAuth: {
- type: "apiKey",
- in: "header",
- name: "Authorization",
+ type: 'apiKey',
+ in: 'header',
+ name: 'Authorization',
},
};
openApiDocument.security = [{ ApiKeyAuth: [] }];
@@ -40,8 +35,7 @@ router.use("/", agentLoader, async (req: any, res) => {
let htmlContent = swaggerUi.generateHTML(openApiDocument);
- let debugScript =
- '<script src="/static/embodiment/swagger/swagger.js"></script>';
+ let debugScript = '<script src="/static/embodiment/swagger/swagger.js"></script>';
if (isTestDomain) {
debugScript += `
<script src="/static/embodiment/swagger/swagger-debug.js"></script>
@@ -52,7 +46,7 @@ initDebug('${config.env.UI_SERVER}', '${agent.id}');
}
//inject the debug script before closing body tag
- htmlContent = htmlContent.replace("</body>", `${debugScript}</body>`);
+ htmlContent = htmlContent.replace('</body>', `${debugScript}</body>`);
res.send(htmlContent);
});
diff --git a/packages/runtime/src/modules/embodiment/routes/index.ts b/packages/runtime/src/modules/embodiment/routes/index.ts
index 1cd245fb..d5411816 100644
--- a/packages/runtime/src/modules/embodiment/routes/index.ts
+++ b/packages/runtime/src/modules/embodiment/routes/index.ts
@@ -1,18 +1,18 @@
-import { Router } from "express";
-import swaggerUi from "swagger-ui-express";
+import { Router } from 'express';
+import swaggerUi from 'swagger-ui-express';
-import config from "@core/config";
+import config from '@core/config';
-import { agentChatRouter } from "@embodiment/modules/agentChat/routes/router";
-import { alexaRouter } from "@embodiment/modules/alexa/routes/router";
-import { apiRouter } from "@embodiment/modules/API/routes/router";
-import { chatBotRouter } from "@embodiment/modules/chatbot/routes/router";
-import { chatGPTRouter } from "@embodiment/modules/chatGPT/routes/router";
-import { formPreviewRouter } from "@embodiment/modules/formPreview/routes/router";
-import { mcpRouter } from "@embodiment/modules/mcp/routes/router";
-import { openaiRouter } from "@embodiment/modules/openai/routes/router";
-import { postmanRouter } from "@embodiment/modules/postman/routes/router";
-import { swaggerRouter } from "@embodiment/modules/swagger/routes/router";
+import { agentChatRouter } from '@embodiment/modules/agentChat/routes/router';
+import { alexaRouter } from '@embodiment/modules/alexa/routes/router';
+import { apiRouter } from '@embodiment/modules/API/routes/router';
+import { chatBotRouter } from '@embodiment/modules/chatbot/routes/router';
+import { chatGPTRouter } from '@embodiment/modules/chatGPT/routes/router';
+import { formPreviewRouter } from '@embodiment/modules/formPreview/routes/router';
+import { mcpRouter } from '@embodiment/modules/mcp/routes/router';
+import { openaiRouter } from '@embodiment/modules/openai/routes/router';
+import { postmanRouter } from '@embodiment/modules/postman/routes/router';
+import { swaggerRouter } from '@embodiment/modules/swagger/routes/router';
const mainRouter = Router();
@@ -24,61 +24,61 @@ type Route = {
const defaultRoutes: Route[] = [
{
- rootPath: ["/_openai", "/emb/openai"],
+ rootPath: ['/_openai', '/emb/openai'],
route: openaiRouter,
},
{
- rootPath: ["/postman", "/emb/postman"],
+ rootPath: ['/postman', '/emb/postman'],
route: postmanRouter,
},
// #region Swagger, we need both
{
- rootPath: ["/swagger", "/emb/swagger"],
+ rootPath: ['/swagger', '/emb/swagger'],
route: swaggerUi.serve,
},
{
- rootPath: ["/swagger", "/emb/swagger"],
+ rootPath: ['/swagger', '/emb/swagger'],
route: swaggerRouter,
},
// #endregion
{
- rootPath: ["/", "/emb/api"],
+ rootPath: ['/', '/emb/api'],
route: apiRouter,
},
{
- rootPath: ["/", "/emb/chatgpt"],
+ rootPath: ['/', '/emb/chatgpt'],
route: chatGPTRouter,
},
{
- rootPath: ["/chatbot", "chatBot", "/emb/chatbot"],
+ rootPath: ['/chatbot', 'chatBot', '/emb/chatbot'],
route: chatBotRouter,
},
{
- rootPath: ["/aichat", "/emb/aichat"],
+ rootPath: ['/aichat', '/emb/aichat'],
route: agentChatRouter,
},
{
- rootPath: ["/alexa", "/emb/alexa"],
+ rootPath: ['/alexa', '/emb/alexa'],
route: alexaRouter,
},
{
- rootPath: ["/mcp", "/emb/mcp"],
+ rootPath: ['/mcp', '/emb/mcp'],
route: mcpRouter,
},
{
- rootPath: ["/form-preview", "/emb/form-preview"],
+ rootPath: ['/form-preview', '/emb/form-preview'],
route: formPreviewRouter,
},
];
const devRoutes: Route[] = [];
-defaultRoutes.forEach((route) => {
+defaultRoutes.forEach(route => {
if (Array.isArray(route.rootPath)) {
- route.rootPath.forEach((path) => {
+ route.rootPath.forEach(path => {
mainRouter.use(path, route.route);
});
} else {
@@ -86,10 +86,10 @@ defaultRoutes.forEach((route) => {
}
});
-if (config.env.NODE_ENV === "development") {
- devRoutes.forEach((route) => {
+if (config.env.NODE_ENV === 'development') {
+ devRoutes.forEach(route => {
if (Array.isArray(route.rootPath)) {
- route.rootPath.forEach((path) => {
+ route.rootPath.forEach(path => {
mainRouter.use(path, route.route);
});
} else {
diff --git a/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts b/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts
index 6552e255..e829138b 100644
--- a/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts
+++ b/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts
@@ -1,22 +1,22 @@
-import { Request } from "express";
+import { Request } from 'express';
-import { Agent, AgentLogger, Conversation } from "@smythos/sre";
+import { Agent, AgentLogger, Conversation } from '@smythos/sre';
-import config from "@core/config";
-import { DEFAULT_MODEL } from "@core/constants";
+import config from '@core/config';
+import { DEFAULT_MODEL } from '@core/constants';
-import { EMBODIMENT_TYPES } from "@embodiment/constants";
+import { EMBODIMENT_TYPES } from '@embodiment/constants';
-import { getOpenAPIJSONForAI } from "../helpers/openapi-adapter.helper";
-import { ChatConversationsEnv } from "../utils/chat.utils";
-import { delay } from "../utils/date-time.utils";
-import { FsChatbotContextStore } from "./FsChatbotContextStore.class";
-import { ConversationStreamYield } from "./FsChatbotContextStore.class/FsChatbotContextExporter.class";
+import { getOpenAPIJSONForAI } from '../helpers/openapi-adapter.helper';
+import { ChatConversationsEnv } from '../utils/chat.utils';
+import { delay } from '../utils/date-time.utils';
+import { FsChatbotContextStore } from './FsChatbotContextStore.class';
+import { ConversationStreamYield } from './FsChatbotContextStore.class/FsChatbotContextExporter.class';
type Headers = {
- "x-conversation-id": string;
+ 'x-conversation-id': string;
Authorization?: string;
- "x-forwarded-for"?: string;
+ 'x-forwarded-for'?: string;
};
type ChatbotResponse = {
@@ -46,46 +46,39 @@ export default class Chatbot {
public embodimentSettings;
private agent: Agent;
- private systemMessage = "";
+ private systemMessage = '';
private model = DEFAULT_MODEL;
private modelInfo: any;
private function_call_order = 0;
private contextWindow = 1024 * 128;
private maxOutputTokens = 4096;
- private client_ip = "";
- private toolCallId = "";
- private logId = "";
- private teamId = "";
+ private client_ip = '';
+ private toolCallId = '';
+ private logId = '';
+ private teamId = '';
private passThroughNotifications = {};
private isAgentChat = false;
constructor(req: Request | any) {
this.agentId = req._agent.id; //from AgentLoader middleware
this.sessionID = req.sessionID;
- this.conversationID = req.headers["x-conversation-id"] || req.sessionID;
+ this.conversationID = req.headers['x-conversation-id'] || req.sessionID;
this.domain = req._agent.domain; //req.hostname;
this.agent = req._agent;
- this.client_ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
+ this.client_ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
this.teamId = req._agent.teamId;
- this.isAgentChat = req.headers["x-ai-agent"] === "true";
+ this.isAgentChat = req.headers['x-ai-agent'] === 'true';
}
public async init() {
// wait for agent settings and embodiments to be ready
await this.agent.agentSettings?.ready();
await this.agent.agentSettings?.embodiments?.ready();
- this.systemMessage =
- this.agent.data.behavior ||
- this.agent.data.description ||
- this.agent.data.shortDescription ||
- "";
+ this.systemMessage = this.agent.data.behavior || this.agent.data.description || this.agent.data.shortDescription || '';
this.model =
- this.agent.agentSettings?.get("chatGptModel") ||
- this.agent.agentSettings?.embodiments?.get(
- EMBODIMENT_TYPES.ChatBot,
- "chatGptModel"
- ) ||
+ this.agent.agentSettings?.get('chatGptModel') ||
+ this.agent.agentSettings?.embodiments?.get(EMBODIMENT_TYPES.ChatBot, 'chatGptModel') ||
this.model;
// Initialize basic modelInfo since LLMRegistry is deprecated
@@ -99,7 +92,7 @@ export default class Chatbot {
// Keep original model ID
// this.model stays as is since SRE handles model resolution
- console.log("modelInfo", this.model, this.modelInfo);
+ console.log('modelInfo', this.model, this.modelInfo);
}
/**
@@ -147,16 +140,8 @@ export default class Chatbot {
* @param errorType - Type of error for categorization
* @param callback - Callback function to send response
*/
- private sendErrorMessage(
- error: any,
- errorType: string,
- callback: (response: ChatbotResponse) => void
- ) {
- const errorMessage =
- error?.message ||
- error?.code ||
- error ||
- "An error occurred. Please try again later.";
+ private sendErrorMessage(error: any, errorType: string, callback: (response: ChatbotResponse) => void) {
+ const errorMessage = error?.message || error?.code || error || 'An error occurred. Please try again later.';
callback({
content: errorMessage,
@@ -185,8 +170,8 @@ export default class Chatbot {
this.function_call_order++;
this.logId = AgentLogger.log(this.agent, null, {
- sourceId: "chat",
- componentId: "CHATBOT",
+ sourceId: 'chat',
+ componentId: 'CHATBOT',
domain: this.domain,
input: message,
inputTimestamp: new Date().toISOString(),
@@ -198,11 +183,7 @@ export default class Chatbot {
.toUpperCase();
try {
- const spec = await getOpenAPIJSONForAI(
- this.domain,
- this.agent.usingTestDomain ? "" : "latest",
- isAgentChatRequest
- );
+ const spec = await getOpenAPIJSONForAI(this.domain, this.agent.usingTestDomain ? '' : 'latest', isAgentChatRequest);
// Adapt the model based on the user's plan, especially to support certain OpenAI models for legacy users with limited tokens without their own API key.
const conversation = new Conversation(this.model, spec, {
@@ -212,24 +193,18 @@ export default class Chatbot {
store: contextStore,
});
- conversation.on("error", (error) => {
- console.error("Error in conversation:", error);
+ conversation.on('error', error => {
+ console.error('Error in conversation:', error);
// Send error as normal content with error flag instead of throwing
- this.sendErrorMessage(error, "conversation_error", callback);
+ this.sendErrorMessage(error, 'conversation_error', callback);
});
- conversation.on("toolInfo", (toolInfo) =>
- this.toolsInfoHandler(toolInfo, callback)
- );
+ conversation.on('toolInfo', toolInfo => this.toolsInfoHandler(toolInfo, callback));
- conversation.on("beforeToolCall", (toolInfo, llmResponse) =>
- this.beforeToolCallHandler(toolInfo, llmResponse, callback)
- );
+ conversation.on('beforeToolCall', (toolInfo, llmResponse) => this.beforeToolCallHandler(toolInfo, llmResponse, callback));
- conversation.on("afterToolCall", (toolInfo, toolResponse) =>
- this.afterToolCallHandler(toolInfo, toolResponse, callback)
- );
+ conversation.on('afterToolCall', (toolInfo, toolResponse) => this.afterToolCallHandler(toolInfo, toolResponse, callback));
// TODO: We need to stream the "thinking" content correctly. Currently, when using callback({..., debug: thinking}), it prints each chunk on a separate line, which doesn't preserve the original format. We need to fix this to maintain the original flow of the "thinking" content.
// conversation.on('thinking', (thinking) => {
@@ -237,37 +212,36 @@ export default class Chatbot {
// });
// Print the thinking content at once
- conversation.on("thoughtProcess", (thinking) => {
+ conversation.on('thoughtProcess', thinking => {
callback({
title: `[${this.toolCallId}] Thought Process`,
debug: thinking,
});
});
- conversation.on("content", (content) => {
+ conversation.on('content', content => {
try {
- if (content?.indexOf("}{") >= 0) {
+ if (content?.indexOf('}{') >= 0) {
// workaround to avoid broken json chunks parsing in the frontend
// since all the json chunks are streamed in the same response, we use "}{" to separate them
// if a content is equal to '}{' or contains it, we replace it with '} {' to avoid false new chunk
- content = content.replace(/}{/g, "} {");
+ content = content.replace(/}{/g, '} {');
}
callback({ content });
} catch (e) {
// Send content processing error as normal message with error flag
- this.sendErrorMessage(e, "content_processing_error", callback);
+ this.sendErrorMessage(e, 'content_processing_error', callback);
}
});
- const isStickyDebug =
- this.agent.debugSessionEnabled || headers["X-MONITOR-ID"];
- const dbgHeaders = isStickyDebug ? { "x-hash-id": this.client_ip } : {};
+ const isStickyDebug = this.agent.debugSessionEnabled || headers['X-MONITOR-ID'];
+ const dbgHeaders = isStickyDebug ? { 'x-hash-id': this.client_ip } : {};
const concurrentToolCalls = this.agent.debugSessionEnabled ? 1 : 4;
const result = await conversation.streamPrompt(
message,
- { "x-caller-session-id": conversationID, ...headers, ...dbgHeaders },
+ { 'x-caller-session-id': conversationID, ...headers, ...dbgHeaders },
concurrentToolCalls,
- abortSignal
+ abortSignal,
);
if (this.logId)
@@ -278,37 +252,30 @@ export default class Chatbot {
} catch (error: any) {
if (this.logId) {
AgentLogger.log(this.agent, this.logId, {
- error: typeof error === "object" ? JSON.stringify(error) : error,
+ error: typeof error === 'object' ? JSON.stringify(error) : error,
});
}
// Send error message as normal system message with error flag
- this.sendErrorMessage(error, "system_error", callback);
+ this.sendErrorMessage(error, 'system_error', callback);
} finally {
- this.logId = "";
- this.toolCallId = "";
+ this.logId = '';
+ this.toolCallId = '';
}
}
- private async toolsInfoHandler(
- toolsInfo,
- callback: (response: ChatbotResponse) => void
- ) {
+ private async toolsInfoHandler(toolsInfo, callback: (response: ChatbotResponse) => void) {
if (this.agent.usingTestDomain || this.isAgentChat) {
for (const tool of toolsInfo) {
const toolHash = tool.id ? fnv1aHash(tool.id) : this.toolCallId;
const dbgJson = {
title: `[${toolHash}] Function Call : ${tool.name}`,
- debug: `${tool.name} (${
- tool?.arguments && typeof tool?.arguments === "object"
- ? JSON.stringify(tool?.arguments)
- : tool?.arguments
- })`,
+ debug: `${tool.name} (${tool?.arguments && typeof tool?.arguments === 'object' ? JSON.stringify(tool?.arguments) : tool?.arguments})`,
};
if (this.agent.debugSessionEnabled) {
//attach to UI debugger
- dbgJson["function"] = "updateStatus";
- dbgJson["parameters"] = ["Debugger: Attaching To Agent ..."];
+ dbgJson['function'] = 'updateStatus';
+ dbgJson['parameters'] = ['Debugger: Attaching To Agent ...'];
}
callback(dbgJson);
@@ -320,11 +287,7 @@ export default class Chatbot {
}
}
- private async beforeToolCallHandler(
- { tool, args },
- llmResponse,
- callback: (response: ChatbotResponse) => void
- ) {
+ private async beforeToolCallHandler({ tool, args }, llmResponse, callback: (response: ChatbotResponse) => void) {
if (this.logId)
AgentLogger.log(this.agent, this.logId, {
output: llmResponse,
@@ -334,16 +297,14 @@ export default class Chatbot {
if (this.agent.usingTestDomain || this.isAgentChat) {
if (this.agent.debugSessionEnabled) {
await delay(100);
- const dbgFunction = `${tool.name} (${
- args && typeof args === "object" ? JSON.stringify(args) : args
- })`;
+ const dbgFunction = `${tool.name} (${args && typeof args === 'object' ? JSON.stringify(args) : args})`;
let dbgJson = {
title: `[${toolHash}] Function Call : ${tool.name}`,
debug: `Debugging ${dbgFunction.substring(0, 50)} ...`,
};
- dbgJson["function"] = "callParentFunction";
- dbgJson["parameters"] = ["debugLastAction", [], 200];
+ dbgJson['function'] = 'callParentFunction';
+ dbgJson['parameters'] = ['debugLastAction', [], 200];
callback(dbgJson);
}
}
@@ -353,16 +314,12 @@ export default class Chatbot {
}
}
- private async afterToolCallHandler(
- { tool, args },
- toolResponse,
- callback: (response: ChatbotResponse) => void
- ) {
+ private async afterToolCallHandler({ tool, args }, toolResponse, callback: (response: ChatbotResponse) => void) {
const toolHash = tool.id ? fnv1aHash(tool.id) : this.toolCallId;
if (this.agent.usingTestDomain || this.isAgentChat) {
//workaround to avoid broken debug message in the frontend
//replace all "}{" with "} {";
- const _toolResponse = toolResponse.replace(/}\{/g, "}_{");
+ const _toolResponse = toolResponse.replace(/}\{/g, '}_{');
const chunkSize = 500;
for (let i = 0, len = _toolResponse.length; i < len; i += chunkSize) {
const chunk = _toolResponse.substr(i, chunkSize);
@@ -412,13 +369,7 @@ export default class Chatbot {
return this.processChatMessage({ message, headers, callback, abortSignal });
} */
- public async *exportAllConversations({
- dateRange,
- env,
- }: {
- dateRange?: string;
- env?: string;
- }): AsyncGenerator<ConversationStreamYield> {
+ public async *exportAllConversations({ dateRange, env }: { dateRange?: string; env?: string }): AsyncGenerator<ConversationStreamYield> {
const contextStore = new FsChatbotContextStore({
agentId: this.agentId,
conversationID: this.conversationID,
diff --git a/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/FsChatbotContextExporter.class.ts b/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/FsChatbotContextExporter.class.ts
index 3e736829..982069d4 100644
--- a/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/FsChatbotContextExporter.class.ts
+++ b/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/FsChatbotContextExporter.class.ts
@@ -1,8 +1,8 @@
-import * as fs from "fs";
-import path from "path";
+import * as fs from 'fs';
+import path from 'path';
-import * as chatUtils from "@embodiment/utils/chat.utils";
-import { fsExists } from "@embodiment/utils/general.utils";
+import * as chatUtils from '@embodiment/utils/chat.utils';
+import { fsExists } from '@embodiment/utils/general.utils';
export type ConversationStreamYield = {
stream: fs.ReadStream;
@@ -13,13 +13,7 @@ export class FsChatbotContextExporter {
private sessionsPath: string;
private agentId: string;
- constructor({
- sessionsPath,
- agentId,
- }: {
- sessionsPath: string;
- agentId: string;
- }) {
+ constructor({ sessionsPath, agentId }: { sessionsPath: string; agentId: string }) {
this.sessionsPath = sessionsPath;
this.agentId = agentId;
}
@@ -38,29 +32,26 @@ export class FsChatbotContextExporter {
}): AsyncGenerator<ConversationStreamYield> {
// TODO covert to stream-based export. will implement it NOW
const folderPath = path.join(this.sessionsPath, this.agentId);
- const testConvprefix = chatUtils.CHAT_PREFIXES["test"];
- const prodConvprefix = chatUtils.CHAT_PREFIXES["prod"];
+ const testConvprefix = chatUtils.CHAT_PREFIXES['test'];
+ const prodConvprefix = chatUtils.CHAT_PREFIXES['prod'];
// check if the folder exists
if (!(await fsExists(folderPath))) return;
const conversations = await fs.promises.readdir(folderPath);
- const filteredConversations = conversations.filter((conversation) => {
+ const filteredConversations = conversations.filter(conversation => {
// first, filter out by prefix env
if (
- env === "test"
+ env === 'test'
? !conversation.startsWith(testConvprefix)
- : conversation.startsWith(testConvprefix) ||
- !conversation.startsWith(prodConvprefix)
+ : conversation.startsWith(testConvprefix) || !conversation.startsWith(prodConvprefix)
)
return false;
- if (!conversation.endsWith(".json")) return false;
+ if (!conversation.endsWith('.json')) return false;
// then, filter out by date range
if (dateRange && chatUtils.isValidDateRange(dateRange)) {
- const conversationDate = chatUtils
- .parseDateFromConvId(conversation)
- .getTime();
+ const conversationDate = chatUtils.parseDateFromConvId(conversation).getTime();
const { start, end } = chatUtils.parseDateRange(dateRange);
if (conversationDate < start || conversationDate > end) return false;
}
@@ -71,8 +62,8 @@ export class FsChatbotContextExporter {
for (const file of filteredConversations) {
const fullPath = path.join(this.sessionsPath, this.agentId, file);
yield {
- stream: fs.createReadStream(fullPath, { encoding: "utf8" }),
- convId: file.replace(".json", ""),
+ stream: fs.createReadStream(fullPath, { encoding: 'utf8' }),
+ convId: file.replace('.json', ''),
};
}
}
diff --git a/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/index.ts b/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/index.ts
index eed4e30d..c445dd77 100644
--- a/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/index.ts
+++ b/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/index.ts
@@ -1,12 +1,12 @@
-import fs from "fs";
-import path from "path";
+import fs from 'fs';
+import path from 'path';
-import type { ILLMContextStore } from "@smythos/sre";
+import type { ILLMContextStore } from '@smythos/sre';
-import { EStorageTypes } from "@embodiment/types/fileStorage.types";
-import { fsExists } from "@embodiment/utils/general.utils";
+import { EStorageTypes } from '@embodiment/types/fileStorage.types';
+import { fsExists } from '@embodiment/utils/general.utils';
-import { FsChatbotContextExporter } from "./FsChatbotContextExporter.class";
+import { FsChatbotContextExporter } from './FsChatbotContextExporter.class';
export class FsChatbotContextStore implements ILLMContextStore {
private agentId: string;
@@ -17,17 +17,9 @@ export class FsChatbotContextStore implements ILLMContextStore {
storageType = EStorageTypes.Local;
private sessionsPath: string;
- constructor({
- agentId,
- conversationID,
- dataPath,
- }: {
- agentId: string;
- conversationID: string;
- dataPath?: string;
- }) {
+ constructor({ agentId, conversationID, dataPath }: { agentId: string; conversationID: string; dataPath?: string }) {
if (!dataPath) {
- throw new Error("dataPath is required.");
+ throw new Error('dataPath is required.');
}
if (!fs.existsSync(dataPath)) {
@@ -37,7 +29,7 @@ export class FsChatbotContextStore implements ILLMContextStore {
this.dataFolder = dataPath;
this.agentId = agentId;
this.conversationID = conversationID;
- this.sessionsPath = path.join(dataPath, "chat_sessions");
+ this.sessionsPath = path.join(dataPath, 'chat_sessions');
this.exporter = new FsChatbotContextExporter({
sessionsPath: this.sessionsPath,
agentId,
@@ -46,30 +38,20 @@ export class FsChatbotContextStore implements ILLMContextStore {
public async save(messages: any[]): Promise<void> {
try {
- const filePath = this.getConversationFilePath(
- this.agentId,
- this.conversationID
- );
+ const filePath = this.getConversationFilePath(this.agentId, this.conversationID);
await this.ensureDirectoryExistence(filePath);
- await fs.promises.writeFile(
- filePath,
- JSON.stringify(messages, null, 2),
- "utf-8"
- );
+ await fs.promises.writeFile(filePath, JSON.stringify(messages, null, 2), 'utf-8');
} catch (error) {
// Saving is not critical, so we can simply log the error and continue without interrupting the process.
- console.warn("Error saving Conversation: ", error);
+ console.warn('Error saving Conversation: ', error);
}
}
public async load(count?: number): Promise<any[]> {
- const conversations = await this.getConversationById(
- this.agentId,
- this.conversationID
- );
+ const conversations = await this.getConversationById(this.agentId, this.conversationID);
if (count === undefined) return conversations;
- if (typeof count === "number" && count > 0) {
+ if (typeof count === 'number' && count > 0) {
return conversations.slice(-count);
}
}
@@ -78,17 +60,14 @@ export class FsChatbotContextStore implements ILLMContextStore {
return {};
}
- private async getConversationById(
- agentId: string,
- conversationId: string
- ): Promise<Record<string, any>[]> {
+ private async getConversationById(agentId: string, conversationId: string): Promise<Record<string, any>[]> {
const folderPath = path.join(this.sessionsPath, agentId);
if (!(await fsExists(folderPath))) {
return [];
}
- const filePath = path.join(folderPath, conversationId + ".json");
+ const filePath = path.join(folderPath, conversationId + '.json');
if (!(await fsExists(filePath))) {
return [];
@@ -96,7 +75,7 @@ export class FsChatbotContextStore implements ILLMContextStore {
try {
const fileContent = await fs.promises.readFile(filePath, {
- encoding: "utf8",
+ encoding: 'utf8',
});
return JSON.parse(fileContent);
} catch (error) {
@@ -104,10 +83,7 @@ export class FsChatbotContextStore implements ILLMContextStore {
}
}
- private getConversationFilePath(
- agentId: string,
- conversationID: string
- ): string {
+ private getConversationFilePath(agentId: string, conversationID: string): string {
return path.join(this.sessionsPath, agentId, `${conversationID}.json`);
}
diff --git a/packages/runtime/src/modules/embodiment/types/chat.types.ts b/packages/runtime/src/modules/embodiment/types/chat.types.ts
index d6f09f01..3771868a 100644
--- a/packages/runtime/src/modules/embodiment/types/chat.types.ts
+++ b/packages/runtime/src/modules/embodiment/types/chat.types.ts
@@ -1,28 +1,28 @@
export enum EChatMessageRole {
- User = 'user',
- System = 'system',
- Assistant = 'assistant',
+ User = 'user',
+ System = 'system',
+ Assistant = 'assistant',
}
export interface IMetadataFile {
- id: string;
- label: string;
- summary: string;
- teamId: string;
- agentId: string;
- chunkSize: number;
- lastChunkId: number;
+ id: string;
+ label: string;
+ summary: string;
+ teamId: string;
+ agentId: string;
+ chunkSize: number;
+ lastChunkId: number;
}
export interface IChatMessage {
- content: string;
- timestamp?: number;
- role: EChatMessageRole;
+ content: string;
+ timestamp?: number;
+ role: EChatMessageRole;
}
export interface IChatStorage {
- exists: (fileName: string) => Promise<boolean>;
- read: (fileName: string) => Promise<string | null>;
- write: (fileName: string, data: string, metadata: Record<any, any>) => Promise<void>;
- setParams: (params: { teamId: string; userId: string; agentId: string; conversationId: string }) => void;
+ exists: (fileName: string) => Promise<boolean>;
+ read: (fileName: string) => Promise<string | null>;
+ write: (fileName: string, data: string, metadata: Record<any, any>) => Promise<void>;
+ setParams: (params: { teamId: string; userId: string; agentId: string; conversationId: string }) => void;
}
diff --git a/packages/runtime/src/modules/embodiment/types/chatgpt.types.ts b/packages/runtime/src/modules/embodiment/types/chatgpt.types.ts
index ccecb046..2bf1775a 100644
--- a/packages/runtime/src/modules/embodiment/types/chatgpt.types.ts
+++ b/packages/runtime/src/modules/embodiment/types/chatgpt.types.ts
@@ -12,39 +12,39 @@ export type ChatGPTAuthType = 'none' | 'oauth' | 'service_http';
* Base authentication interface
*/
export interface ChatGPTAuthBase {
- type: ChatGPTAuthType;
+ type: ChatGPTAuthType;
}
/**
* No authentication required
*/
export interface ChatGPTAuthNone extends ChatGPTAuthBase {
- type: 'none';
+ type: 'none';
}
/**
* OAuth authentication configuration
*/
export interface ChatGPTAuthOAuth extends ChatGPTAuthBase {
- type: 'oauth';
- client_url: string;
- scope: string;
- authorization_url: string;
- authorization_content_type: string;
- verification_tokens?: {
- openai?: string;
- };
+ type: 'oauth';
+ client_url: string;
+ scope: string;
+ authorization_url: string;
+ authorization_content_type: string;
+ verification_tokens?: {
+ openai?: string;
+ };
}
/**
* Service HTTP authentication (Bearer token)
*/
export interface ChatGPTAuthServiceHttp extends ChatGPTAuthBase {
- type: 'service_http';
- authorization_type: 'bearer';
- verification_tokens?: {
- openai?: string;
- };
+ type: 'service_http';
+ authorization_type: 'bearer';
+ verification_tokens?: {
+ openai?: string;
+ };
}
/**
@@ -56,82 +56,82 @@ export type ChatGPTAuth = ChatGPTAuthNone | ChatGPTAuthOAuth | ChatGPTAuthServic
* API configuration for the plugin
*/
export interface ChatGPTAPI {
- type: 'openapi';
- url: string;
- is_user_authenticated: boolean;
+ type: 'openapi';
+ url: string;
+ is_user_authenticated: boolean;
}
/**
* Complete ChatGPT Plugin Manifest structure
*/
export interface ChatGPTManifest {
- /** Schema version of the manifest */
- schema_version: 'v1';
+ /** Schema version of the manifest */
+ schema_version: 'v1';
- /** Human-readable name for the plugin */
- name_for_human: string;
+ /** Human-readable name for the plugin */
+ name_for_human: string;
- /** Name used by the model to reference the plugin */
- name_for_model: string;
+ /** Name used by the model to reference the plugin */
+ name_for_model: string;
- /** Human-readable description of the plugin */
- description_for_human: string;
+ /** Human-readable description of the plugin */
+ description_for_human: string;
- /** Model-focused description of the plugin's capabilities */
- description_for_model: string;
+ /** Model-focused description of the plugin's capabilities */
+ description_for_model: string;
- /** Authentication configuration */
- auth: ChatGPTAuth;
+ /** Authentication configuration */
+ auth: ChatGPTAuth;
- /** API specification */
- api: ChatGPTAPI;
+ /** API specification */
+ api: ChatGPTAPI;
- /** URL to the plugin's logo */
- logo_url: string;
+ /** URL to the plugin's logo */
+ logo_url: string;
- /** Contact email for the plugin */
- contact_email: string;
+ /** Contact email for the plugin */
+ contact_email: string;
- /** URL to legal information about the plugin */
- legal_info_url: string;
+ /** URL to legal information about the plugin */
+ legal_info_url: string;
}
/**
* Template variables used for generating the manifest
*/
export interface ChatGPTManifestTemplate {
- human_name: string;
- model_name: string;
- human_description: string;
- model_description: string;
- icon_url: string;
- contact_email: string;
- legal_info_url: string;
- domain: string;
+ human_name: string;
+ model_name: string;
+ human_description: string;
+ model_description: string;
+ icon_url: string;
+ contact_email: string;
+ legal_info_url: string;
+ domain: string;
}
/**
* ChatGPT embodiment properties from agent configuration
*/
export interface ChatGPTEmbodimentProperties {
- /** Description for the model */
- modelDescription?: string;
+ /** Description for the model */
+ modelDescription?: string;
- /** Human-readable name */
- humanName?: string;
+ /** Human-readable name */
+ humanName?: string;
- /** Model name */
- modelName?: string;
+ /** Model name */
+ modelName?: string;
- /** Human-readable description */
- humanDescription?: string;
+ /** Human-readable description */
+ humanDescription?: string;
- /** Contact email */
- contactEmail?: string;
+ /** Contact email */
+ contactEmail?: string;
- /** Legal information URL */
- legalInfoUrl?: string;
+ /** Legal information URL */
+ legalInfoUrl?: string;
- /** Logo URL */
- logoUrl?: string;
+ /** Logo URL */
+ logoUrl?: string;
}
diff --git a/packages/runtime/src/modules/embodiment/types/fileStorage.types.ts b/packages/runtime/src/modules/embodiment/types/fileStorage.types.ts
index adf5b812..bb662904 100644
--- a/packages/runtime/src/modules/embodiment/types/fileStorage.types.ts
+++ b/packages/runtime/src/modules/embodiment/types/fileStorage.types.ts
@@ -1,4 +1,4 @@
export enum EStorageTypes {
- Local = 'local',
- Remote = 'remote',
+ Local = 'local',
+ Remote = 'remote',
}
diff --git a/packages/runtime/src/modules/embodiment/utils/apiError.ts b/packages/runtime/src/modules/embodiment/utils/apiError.ts
index 95b231ee..6779e08a 100644
--- a/packages/runtime/src/modules/embodiment/utils/apiError.ts
+++ b/packages/runtime/src/modules/embodiment/utils/apiError.ts
@@ -8,33 +8,33 @@
*/
class ApiError extends Error {
- statusCode: number | null | undefined;
+ statusCode: number | null | undefined;
- isOperational: boolean;
+ isOperational: boolean;
- stack: string | undefined;
+ stack: string | undefined;
- errKey: string | undefined;
+ errKey: string | undefined;
- isApiError: boolean;
+ 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
- */
+ /**
+ *
+ * @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;
- }
+ // 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/runtime/src/modules/embodiment/utils/chat.utils.ts b/packages/runtime/src/modules/embodiment/utils/chat.utils.ts
index 4430f81b..8580259c 100644
--- a/packages/runtime/src/modules/embodiment/utils/chat.utils.ts
+++ b/packages/runtime/src/modules/embodiment/utils/chat.utils.ts
@@ -2,32 +2,32 @@ import crypto from 'crypto';
import { getCurrentFormattedDate, toDateFromFormattedDateStr } from './date-time.utils';
export type ChatConversationsEnv = 'test' | 'prod';
export const CHAT_PREFIXES: Record<ChatConversationsEnv, string> = {
- test: 'chat-test-',
- prod: 'chat-',
+ test: 'chat-test-',
+ prod: 'chat-',
};
export const buildConversationId = (uid?: string, isTestConv = false) => {
- const prefix = isTestConv ? CHAT_PREFIXES.test : CHAT_PREFIXES.prod;
- const convId = uid ?? `${prefix}${getCurrentFormattedDate()}-${crypto.randomBytes(8).toString('hex')}`;
- return `${prefix}${getCurrentFormattedDate()}-${convId}`;
+ const prefix = isTestConv ? CHAT_PREFIXES.test : CHAT_PREFIXES.prod;
+ const convId = uid ?? `${prefix}${getCurrentFormattedDate()}-${crypto.randomBytes(8).toString('hex')}`;
+ return `${prefix}${getCurrentFormattedDate()}-${convId}`;
};
export const parseDateFromConvId = (convId: string) => {
- const match = convId.match(/\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}/);
+ const match = convId.match(/\d{4}-\d{2}-\d{2}-\d{2}-\d{2}-\d{2}/);
- if (!match) return null;
- return toDateFromFormattedDateStr(match[0]);
+ if (!match) return null;
+ return toDateFromFormattedDateStr(match[0]);
};
export const getChatPrefixByEnv = (env: ChatConversationsEnv) => {
- return CHAT_PREFIXES[env];
+ return CHAT_PREFIXES[env];
};
export const parseDateRange = (dateRange: string) => {
- const [start, end] = dateRange.split(',');
- return { start: parseInt(start), end: parseInt(end) };
+ const [start, end] = dateRange.split(',');
+ return { start: parseInt(start), end: parseInt(end) };
};
export const isValidDateRange = (dateRange: string) => {
- if (!dateRange) return false;
- const { start, end } = parseDateRange(dateRange);
- return !isNaN(start) && !isNaN(end) && start < end;
+ if (!dateRange) return false;
+ const { start, end } = parseDateRange(dateRange);
+ return !isNaN(start) && !isNaN(end) && start < end;
};
diff --git a/packages/runtime/src/modules/embodiment/utils/date-time.utils copy.ts b/packages/runtime/src/modules/embodiment/utils/date-time.utils copy.ts
index 9184e5d5..d53904a6 100644
--- a/packages/runtime/src/modules/embodiment/utils/date-time.utils copy.ts
+++ b/packages/runtime/src/modules/embodiment/utils/date-time.utils copy.ts
@@ -1,27 +1,27 @@
export function getCurrentFormattedDate() {
- const date = new Date();
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
- const day = String(date.getDate()).padStart(2, '0');
- const hours = String(date.getHours()).padStart(2, '0');
- const minutes = String(date.getMinutes()).padStart(2, '0');
- const seconds = String(date.getSeconds()).padStart(2, '0');
- return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
+ const date = new Date();
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
+ const day = String(date.getDate()).padStart(2, '0');
+ const hours = String(date.getHours()).padStart(2, '0');
+ const minutes = String(date.getMinutes()).padStart(2, '0');
+ const seconds = String(date.getSeconds()).padStart(2, '0');
+ return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
}
export function toDateFromFormattedDateStr(formattedDate: string) {
- const [year, month, day, hour, minute, second] = formattedDate.split('-').map(Number);
- return new Date(year, month - 1, day, hour, minute, second);
+ const [year, month, day, hour, minute, second] = formattedDate.split('-').map(Number);
+ return new Date(year, month - 1, day, hour, minute, second);
}
export function getDayFormattedDate() {
- const date = new Date();
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
- const day = String(date.getDate()).padStart(2, '0');
- return `${year}-${month}-${day}`;
+ const date = new Date();
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
+ const day = String(date.getDate()).padStart(2, '0');
+ return `${year}-${month}-${day}`;
}
export function delay(ms) {
- return new Promise((r) => setTimeout(r, ms));
+ return new Promise(r => setTimeout(r, ms));
}
diff --git a/packages/runtime/src/modules/embodiment/utils/date-time.utils.ts b/packages/runtime/src/modules/embodiment/utils/date-time.utils.ts
index 9184e5d5..d53904a6 100644
--- a/packages/runtime/src/modules/embodiment/utils/date-time.utils.ts
+++ b/packages/runtime/src/modules/embodiment/utils/date-time.utils.ts
@@ -1,27 +1,27 @@
export function getCurrentFormattedDate() {
- const date = new Date();
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
- const day = String(date.getDate()).padStart(2, '0');
- const hours = String(date.getHours()).padStart(2, '0');
- const minutes = String(date.getMinutes()).padStart(2, '0');
- const seconds = String(date.getSeconds()).padStart(2, '0');
- return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
+ const date = new Date();
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
+ const day = String(date.getDate()).padStart(2, '0');
+ const hours = String(date.getHours()).padStart(2, '0');
+ const minutes = String(date.getMinutes()).padStart(2, '0');
+ const seconds = String(date.getSeconds()).padStart(2, '0');
+ return `${year}-${month}-${day}-${hours}-${minutes}-${seconds}`;
}
export function toDateFromFormattedDateStr(formattedDate: string) {
- const [year, month, day, hour, minute, second] = formattedDate.split('-').map(Number);
- return new Date(year, month - 1, day, hour, minute, second);
+ const [year, month, day, hour, minute, second] = formattedDate.split('-').map(Number);
+ return new Date(year, month - 1, day, hour, minute, second);
}
export function getDayFormattedDate() {
- const date = new Date();
- const year = date.getFullYear();
- const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
- const day = String(date.getDate()).padStart(2, '0');
- return `${year}-${month}-${day}`;
+ const date = new Date();
+ const year = date.getFullYear();
+ const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-based
+ const day = String(date.getDate()).padStart(2, '0');
+ return `${year}-${month}-${day}`;
}
export function delay(ms) {
- return new Promise((r) => setTimeout(r, ms));
+ return new Promise(r => setTimeout(r, ms));
}
diff --git a/packages/runtime/src/modules/embodiment/utils/general.utils.ts b/packages/runtime/src/modules/embodiment/utils/general.utils.ts
index 75de713d..d12e03dc 100644
--- a/packages/runtime/src/modules/embodiment/utils/general.utils.ts
+++ b/packages/runtime/src/modules/embodiment/utils/general.utils.ts
@@ -1,52 +1,52 @@
import fs from 'fs/promises';
export function uid() {
- return (Date.now() + Math.random()).toString(36).replace('.', '').toUpperCase();
+ return (Date.now() + Math.random()).toString(36).replace('.', '').toUpperCase();
}
export const hasKeyTemplateVar = (str: string = ''): boolean => {
- if (!str || typeof str !== 'string') return false;
- return (str?.match(/{{KEY\((.*?)\)}}/g) ?? []).length > 0;
+ if (!str || typeof str !== 'string') return false;
+ return (str?.match(/{{KEY\((.*?)\)}}/g) ?? []).length > 0;
};
export function parseTemplate(str, obj, { escapeString = true, processUnmatched = true, unmached = '' } = {}) {
- try {
- const parsed = str?.replace(/{{(.*?)}}/g, function (match, varName) {
- // if key template var, return as is
- if (hasKeyTemplateVar(match)) return match;
-
- let objVal = obj[varName.trim()];
-
- if (typeof objVal === 'object') {
- objVal = JSON.stringify(objVal);
- } else {
- if (escapeString && typeof objVal === 'string') {
- //escape double quotes, slashes ...
- objVal = objVal?.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t');
- }
- }
-
- // Need to consider boolean 'false' as a valid value
- // const val = objVal || match;
- const val = objVal !== undefined ? objVal : match;
-
- return typeof val == 'string' || typeof val == 'number' ? val : JSON.stringify(val);
- });
-
- //replace unmached vars with default value, make sure to ignore the key template var
- return str == parsed && processUnmatched ? parsed?.replace(/{{(?!KEY\().*?}}/g, unmached) : parsed;
- } catch (err) {
- console.log('Error on parse template: ', err);
-
- return str;
- }
+ try {
+ const parsed = str?.replace(/{{(.*?)}}/g, function (match, varName) {
+ // if key template var, return as is
+ if (hasKeyTemplateVar(match)) return match;
+
+ let objVal = obj[varName.trim()];
+
+ if (typeof objVal === 'object') {
+ objVal = JSON.stringify(objVal);
+ } else {
+ if (escapeString && typeof objVal === 'string') {
+ //escape double quotes, slashes ...
+ objVal = objVal?.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\t/g, '\\t');
+ }
+ }
+
+ // Need to consider boolean 'false' as a valid value
+ // const val = objVal || match;
+ const val = objVal !== undefined ? objVal : match;
+
+ return typeof val == 'string' || typeof val == 'number' ? val : JSON.stringify(val);
+ });
+
+ //replace unmached vars with default value, make sure to ignore the key template var
+ return str == parsed && processUnmatched ? parsed?.replace(/{{(?!KEY\().*?}}/g, unmached) : parsed;
+ } catch (err) {
+ console.log('Error on parse template: ', err);
+
+ return str;
+ }
}
export const fsExists = async (path: string) => {
- try {
- await fs.access(path);
- return true;
- } catch {
- return false;
- }
+ try {
+ await fs.access(path);
+ return true;
+ } catch {
+ return false;
+ }
};
diff --git a/packages/runtime/src/services/code-sandbox.service.ts b/packages/runtime/src/services/code-sandbox.service.ts
index 9d26a950..99ccd1a4 100644
--- a/packages/runtime/src/services/code-sandbox.service.ts
+++ b/packages/runtime/src/services/code-sandbox.service.ts
@@ -1,9 +1,9 @@
-import { ChildProcess, spawn } from "child_process";
-import path from "path";
+import { ChildProcess, spawn } from 'child_process';
+import path from 'path';
-import { Logger } from "@smythos/sre";
+import { Logger } from '@smythos/sre';
-const console = Logger("code-sandbox-service");
+const console = Logger('code-sandbox-service');
export class CodeSandboxService {
private static instance: CodeSandboxService;
@@ -19,56 +19,49 @@ export class CodeSandboxService {
async start(): Promise<void> {
try {
- const scriptPath = path.join(
- process.cwd(),
- "..",
- "code-sandbox",
- "index.js"
- );
+ const scriptPath = path.join(process.cwd(), '..', 'code-sandbox', 'index.js');
console.info(`Starting code sandbox service on port ${this.sandboxPort}`);
- this.sandboxProcess = spawn("node", [scriptPath], {
- stdio: ["inherit", "pipe", "pipe"],
+ this.sandboxProcess = spawn('node', [scriptPath], {
+ stdio: ['inherit', 'pipe', 'pipe'],
env: { ...process.env },
});
- this.sandboxProcess.stdout?.on("data", (data) => {
+ this.sandboxProcess.stdout?.on('data', data => {
console.info(`[Code Sandbox] ${data.toString().trim()}`);
});
- this.sandboxProcess.stderr?.on("data", (data) => {
+ this.sandboxProcess.stderr?.on('data', data => {
console.error(`[Code Sandbox Error] ${data.toString().trim()}`);
});
- this.sandboxProcess.on("exit", (code, signal) => {
- console.warn(
- `Code sandbox process exited with code ${code} and signal ${signal}`
- );
+ this.sandboxProcess.on('exit', (code, signal) => {
+ console.warn(`Code sandbox process exited with code ${code} and signal ${signal}`);
this.sandboxProcess = null;
});
- this.sandboxProcess.on("error", (error) => {
- console.error("Failed to start code sandbox process:", error);
+ this.sandboxProcess.on('error', error => {
+ console.error('Failed to start code sandbox process:', error);
});
// Give it a moment to start
- await new Promise((resolve) => setTimeout(resolve, 2000));
+ await new Promise(resolve => setTimeout(resolve, 2000));
- console.info("Code sandbox service started successfully");
+ console.info('Code sandbox service started successfully');
} catch (error) {
- console.error("Failed to start code sandbox service:", error);
+ console.error('Failed to start code sandbox service:', error);
throw error;
}
}
async stop(): Promise<void> {
if (this.sandboxProcess) {
- console.info("Stopping code sandbox service");
- this.sandboxProcess.kill("SIGTERM");
+ console.info('Stopping code sandbox service');
+ this.sandboxProcess.kill('SIGTERM');
// Wait for graceful shutdown, then force kill if needed
- await new Promise((resolve) => {
+ await new Promise(resolve => {
if (!this.sandboxProcess) {
resolve(undefined);
return;
@@ -76,13 +69,13 @@ export class CodeSandboxService {
const timeout = setTimeout(() => {
if (this.sandboxProcess) {
- console.warn("Force killing code sandbox process");
- this.sandboxProcess.kill("SIGKILL");
+ console.warn('Force killing code sandbox process');
+ this.sandboxProcess.kill('SIGKILL');
}
resolve(undefined);
}, 5000);
- this.sandboxProcess.on("exit", () => {
+ this.sandboxProcess.on('exit', () => {
clearTimeout(timeout);
resolve(undefined);
});
diff --git a/packages/runtime/tests/core/utils/chat.utils.test.ts b/packages/runtime/tests/core/utils/chat.utils.test.ts
index dcff75f2..66afbec7 100644
--- a/packages/runtime/tests/core/utils/chat.utils.test.ts
+++ b/packages/runtime/tests/core/utils/chat.utils.test.ts
@@ -75,7 +75,7 @@ describe('Chat Utils', () => {
it('should parse date from conversation ID', () => {
const convId = 'chat-2023-12-25-15-30-45-some-suffix';
const result = parseDateFromConvId(convId);
-
+
expect(result).toBeInstanceOf(Date);
expect(result?.getFullYear()).toBe(2023);
expect(result?.getMonth()).toBe(11); // December (0-based)
@@ -91,7 +91,7 @@ describe('Chat Utils', () => {
it('should parse date from test conversation ID', () => {
const convId = 'chat-test-2024-01-01-12-00-00-test-suffix';
const result = parseDateFromConvId(convId);
-
+
expect(result).toBeInstanceOf(Date);
expect(result?.getFullYear()).toBe(2024);
expect(result?.getMonth()).toBe(0); // January (0-based)
@@ -170,7 +170,7 @@ describe('Chat Utils', () => {
it('should create conversation ID that can be parsed for date', () => {
const convId = buildConversationId();
const parsedDate = parseDateFromConvId(convId);
-
+
expect(parsedDate).toBeInstanceOf(Date);
expect(parsedDate?.getFullYear()).toBe(2023);
expect(parsedDate?.getMonth()).toBe(11); // December
@@ -181,9 +181,9 @@ describe('Chat Utils', () => {
const convId = buildConversationId(undefined, true);
const parsedDate = parseDateFromConvId(convId);
const prefix = getChatPrefixByEnv('test');
-
+
expect(convId.startsWith(prefix)).toBe(true);
expect(parsedDate).toBeInstanceOf(Date);
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/runtime/tests/core/utils/date-time.utils.test.ts b/packages/runtime/tests/core/utils/date-time.utils.test.ts
index 0ff9e5b2..3723c00c 100644
--- a/packages/runtime/tests/core/utils/date-time.utils.test.ts
+++ b/packages/runtime/tests/core/utils/date-time.utils.test.ts
@@ -2,12 +2,7 @@
* Unit tests for date-time utilities
*/
import { describe, it, expect, beforeEach, vi } from 'vitest';
-import {
- getCurrentFormattedDate,
- toDateFromFormattedDateStr,
- getDayFormattedDate,
- delay,
-} from '@core/utils/date-time.utils';
+import { getCurrentFormattedDate, toDateFromFormattedDateStr, getDayFormattedDate, delay } from '@core/utils/date-time.utils';
describe('Date-Time Utils', () => {
beforeEach(() => {
@@ -80,7 +75,7 @@ describe('Date-Time Utils', () => {
it('should return current date only', () => {
const now = new Date();
const result = getDayFormattedDate();
-
+
const [year, month, day] = result.split('-').map(Number);
expect(year).toBe(now.getFullYear());
expect(month).toBe(now.getMonth() + 1);
@@ -101,14 +96,16 @@ describe('Date-Time Utils', () => {
describe('delay', () => {
it('should resolve after the specified milliseconds', async () => {
vi.useFakeTimers();
-
+
const promise = delay(1000);
expect(promise).toBeInstanceOf(Promise);
vi.advanceTimersByTime(500);
// Promise should still be pending
let resolved = false;
- promise.then(() => { resolved = true; });
+ promise.then(() => {
+ resolved = true;
+ });
await Promise.resolve(); // Allow microtasks to run
expect(resolved).toBe(false);
@@ -123,18 +120,18 @@ describe('Date-Time Utils', () => {
const start = Date.now();
await delay(0);
const end = Date.now();
-
+
// Should resolve almost immediately
expect(end - start).toBeLessThan(10);
});
it('should work with non-integer values', async () => {
vi.useFakeTimers();
-
+
const promise = delay(100.5);
vi.advanceTimersByTime(100.5);
await promise;
-
+
// Should not throw an error
expect(true).toBe(true);
@@ -151,10 +148,10 @@ describe('Date-Time Utils', () => {
// The dates should be very close (within a second or two)
const originalParts = original.split('-').map(Number);
const backParts = backToString.split('-').map(Number);
-
+
expect(originalParts[0]).toBe(backParts[0]); // Year
expect(originalParts[1]).toBe(backParts[1]); // Month
expect(originalParts[2]).toBe(backParts[2]); // Day
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/runtime/tests/core/utils/general.utils.test.ts b/packages/runtime/tests/core/utils/general.utils.test.ts
index 797c1a55..04fec523 100644
--- a/packages/runtime/tests/core/utils/general.utils.test.ts
+++ b/packages/runtime/tests/core/utils/general.utils.test.ts
@@ -2,12 +2,7 @@
* Tests for general utilities - following KISS principle
*/
import { describe, it, expect, vi } from 'vitest';
-import {
- uid,
- hasKeyTemplateVar,
- parseTemplate,
- fsExists,
-} from '@core/utils/general.utils';
+import { uid, hasKeyTemplateVar, parseTemplate, fsExists } from '@core/utils/general.utils';
vi.mock('fs/promises', () => ({
default: { access: vi.fn() },
@@ -18,7 +13,7 @@ describe('General Utils', () => {
it('generates unique strings', () => {
const id1 = uid();
const id2 = uid();
-
+
expect(id1).not.toBe(id2);
expect(id1).toMatch(/^[A-Z0-9]+$/);
});
@@ -53,7 +48,7 @@ describe('General Utils', () => {
it('returns true when file exists', async () => {
const fs = await import('fs/promises');
(fs.default.access as any).mockResolvedValue(undefined);
-
+
const result = await fsExists('/test/path');
expect(result).toBe(true);
});
@@ -61,9 +56,9 @@ describe('General Utils', () => {
it('returns false when file does not exist', async () => {
const fs = await import('fs/promises');
(fs.default.access as any).mockRejectedValue(new Error('ENOENT'));
-
+
const result = await fsExists('/missing');
expect(result).toBe(false);
});
});
-});
\ No newline at end of file
+});
diff --git a/packages/runtime/vitest.config.ts b/packages/runtime/vitest.config.ts
index b9aee37c..f59b659b 100644
--- a/packages/runtime/vitest.config.ts
+++ b/packages/runtime/vitest.config.ts
@@ -1,18 +1,18 @@
-import { defineConfig } from "vitest/config";
-import tsconfigPaths from "vite-tsconfig-paths";
+import { defineConfig } from 'vitest/config';
+import tsconfigPaths from 'vite-tsconfig-paths';
export default defineConfig({
plugins: [tsconfigPaths()],
test: {
globals: true,
- environment: "node",
- include: ["tests/**/*.test.ts"],
- exclude: ["node_modules"],
+ environment: 'node',
+ include: ['tests/**/*.test.ts'],
+ exclude: ['node_modules'],
coverage: {
- reporter: ["text", "text-summary", "html"],
- reportsDirectory: "./coverage",
- include: ["src/**/*.{ts,tsx}"],
- exclude: ["node_modules"],
+ reporter: ['text', 'text-summary', 'html'],
+ reportsDirectory: './coverage',
+ include: ['src/**/*.{ts,tsx}'],
+ exclude: ['node_modules'],
},
testTimeout: 30_000,
},