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.

fix ESLint errors

Forhad Hosain206f489e5ed5
diff --git a/packages/runtime/package.json b/packages/runtime/package.json
index c5e44b40..1aa1246c 100644
--- a/packages/runtime/package.json
+++ b/packages/runtime/package.json
@@ -12,9 +12,9 @@
"clean": "rm -rf dist",
"lint": "eslint --ext .ts src/",
"lint-fix": "eslint --ext .ts src/ --fix",
+ "lint-staged": "lint-staged",
"ts-error-scan": "tsc --noEmit",
"prettier:format": "prettier --write \"**/*.ts\"",
- "lint-staged": "lint-staged",
"bump": "pnpm version patch"
},
"author": "Alaa-eddine KADDOURI",
diff --git a/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts b/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts
index 3fc900b4..f9c07e7f 100644
--- a/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts
+++ b/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts
@@ -18,7 +18,7 @@ import { SmythConfigs } from '@core/types/general.types';
const console = Logger('SmythOSSAccount');
export class SmythOSSAccount extends AccountConnector {
- public name: string = 'SmythOSSAccount';
+ public name = 'SmythOSSAccount';
private oAuthAppId: string;
private oAuthAppSecret: string;
private oAuthBaseUrl: string;
@@ -28,7 +28,7 @@ export class SmythOSSAccount extends AccountConnector {
constructor(protected _settings: SmythConfigs & OAuthConfig) {
super(_settings);
- //if (!SmythRuntime.Instance) throw new Error('SRE not initialized');
+ // if (!SmythRuntime.Instance) throw new Error('SRE not initialized');
this.oAuthAppId = _settings.oAuthAppID;
this.oAuthAppSecret = _settings.oAuthAppSecret;
diff --git a/packages/runtime/src/core/connectors/SmythOSSAgentDataConnector.class.ts b/packages/runtime/src/core/connectors/SmythOSSAgentDataConnector.class.ts
index 5f784462..84766b1d 100644
--- a/packages/runtime/src/core/connectors/SmythOSSAgentDataConnector.class.ts
+++ b/packages/runtime/src/core/connectors/SmythOSSAgentDataConnector.class.ts
@@ -6,7 +6,7 @@ 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 = 'SmythOSSAgentData';
private oAuthAppId: string;
private oAuthAppSecret: string;
private oAuthBaseUrl: string;
@@ -18,7 +18,7 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
constructor(private config: SmythConfigs & OAuthConfig & { agentStageDomain: string; agentProdDomain: string }) {
super();
- //if (!SmythRuntime.Instance) throw new Error('SRE not initialized');
+ // if (!SmythRuntime.Instance) throw new Error('SRE not initialized');
this.oAuthAppId = config.oAuthAppID;
this.oAuthAppSecret = config.oAuthAppSecret;
this.oAuthBaseUrl = config.oAuthBaseUrl;
@@ -40,15 +40,14 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
public async getAgentData(agentId: string, version?: string): Promise<any> {
try {
- let agentObj;
-
- //FIXME : once we have the agent name in deployment api response, we can skip this call
+ // 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(),
});
- agentObj = response.data.agent;
- const authData = agentObj.data.auth; //use most up to date auth data
+ // eslint-disable-next-line prefer-const
+ let 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`, {
@@ -56,7 +55,7 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
});
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));
@@ -73,45 +72,45 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
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.debugSessionEnabled = false; // never enable debug session when using a deployed version
agentObj.data.agentVersion = deployment.version;
agentObj.version = deployment.version;
} else {
- //if (version !== 'latest') {
+ // if (version !== 'latest') {
throw new Error(`Requested Deploy Version not found: ${version}`);
- //} // if version == 'latest' but no deployment is found we just fallback to the agent live data
+ // } // if version == 'latest' but no deployment is found we just fallback to the agent live data
}
}
- //TODO: Also include team and subscription info
+ // TODO: Also include team and subscription info
- //agentObj.data.auth = authData;
+ // 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}`);
+ // 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}`);
}
}
public async getAgentIdByDomain(domain: string): Promise<string> {
let agentId;
- //first check if this is the internal wildcard agents domain
+ // first check if this is the internal wildcard agents domain
const isStageWildcardDomain = domain.includes(this.agentStageDomain);
const isProdWildcardDomain = domain.includes(this.agentProdDomain);
if (isStageWildcardDomain || isProdWildcardDomain) {
- //console.log('Internal agent domain detected', domain);
+ // console.log('Internal agent domain detected', domain);
agentId = domain.split('.')[0];
- //sanity check
+ // sanity check
if (`${agentId}.${this.agentStageDomain}` !== domain && `${agentId}.${this.agentProdDomain}` !== domain) {
throw new Error(`Invalid agent domain: ${domain}`);
}
- //if this is a stage domain, no more check, return the agentId
+ // if this is a stage domain, no more check, return the agentId
if (isStageWildcardDomain) return agentId;
}
@@ -126,7 +125,7 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
throw new Error('Error getting domain info');
}
- //we have an agentId from the wildcard domain, if this domain is already associated with
+ // 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);
if (hasDomain) {
@@ -136,12 +135,12 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
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
+ // if a custom domain is found, use it, otherwise use the agentId from the wildcard domain
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`, {
@@ -151,12 +150,12 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
return formattedSettings;
} catch (error) {
- console.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}`, {
@@ -165,7 +164,7 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
return response?.data?.embodiments || [];
} catch (error) {
- console.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}`);
}
}
@@ -184,7 +183,7 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
return agentsList;
} catch (error) {
- console.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}`);
}
}
@@ -196,7 +195,7 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
});
return deploymentsList?.data?.deployments?.length > 0;
} catch (error) {
- console.error(error);
+ // console.error(error);
return false;
}
}
@@ -215,10 +214,10 @@ 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) {
+ for (const component of newData.components) {
component.outputs = component.connectors;
component.inputs = component.receptors;
component.outputProps = component.connectorProps;
@@ -232,10 +231,10 @@ export class SmythOSSAgentDataConnector extends AgentDataConnector {
}
if (data.version === '1.0.0') {
- //migrate .description to .behavior
+ // migrate .description to .behavior
if (data.description && !data.behavior) {
- data.behavior = data.description;
- //delete newConfig.description;
+ const newData = { ...data, behavior: data.description };
+ return newData;
}
}
diff --git a/packages/runtime/src/core/connectors/SmythOSSVault.class.ts b/packages/runtime/src/core/connectors/SmythOSSVault.class.ts
index 864a426a..0818e014 100644
--- a/packages/runtime/src/core/connectors/SmythOSSVault.class.ts
+++ b/packages/runtime/src/core/connectors/SmythOSSVault.class.ts
@@ -21,7 +21,7 @@ type SmythVaultConfig = {
const console = Logger('SmythOSSVault');
export class SmythOSSVault extends VaultConnector {
- public name: string = 'SmythOSSVault';
+ public name = 'SmythOSSVault';
private oAuthAppId: string;
private oAuthAppSecret: string;
private oAuthBaseUrl: string;
@@ -31,7 +31,7 @@ export class SmythOSSVault extends VaultConnector {
constructor(protected _settings: SmythVaultConfig & OAuthConfig) {
super(_settings);
- //if (!SmythRuntime.Instance) throw new Error('SRE not initialized');
+ // if (!SmythRuntime.Instance) throw new Error('SRE not initialized');
this.oAuthAppId = _settings.oAuthAppID;
this.oAuthAppSecret = _settings.oAuthAppSecret;
@@ -81,12 +81,12 @@ export class SmythOSSVault extends VaultConnector {
const teamId = await accountConnector.getCandidateTeam(acRequest.candidate);
const vaultAPIHeaders = await this.getVaultRequestHeaders();
const vaultResponse = await this.vaultAPI.get(`/vault/${teamId}/secrets/${keyId}`, { headers: vaultAPIHeaders });
- return vaultResponse?.data?.secret ? true : false;
+ return !!vaultResponse?.data?.secret;
}
@SecureConnector.AccessControl
protected async listKeys(acRequest: AccessRequest) {
- //const accountConnector = ConnectorService.getAccountConnector();
+ // const accountConnector = ConnectorService.getAccountConnector();
const teamId = acRequest.candidate.id;
const vaultAPIHeaders = await this.getVaultRequestHeaders();
const vaultResponse = await this.vaultAPI.get(`/vault/${teamId}/secrets`, {
diff --git a/packages/runtime/src/core/helpers/agent.helper.ts b/packages/runtime/src/core/helpers/agent.helper.ts
index 40643088..b84ef970 100644
--- a/packages/runtime/src/core/helpers/agent.helper.ts
+++ b/packages/runtime/src/core/helpers/agent.helper.ts
@@ -1,13 +1,12 @@
import axios from 'axios';
import config from '../config';
-import { Logger } from '@smythos/sre';
+import { Logger, AccessCandidate, ConnectorService } from '@smythos/sre';
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';
const logger = Logger('(Core) Service: Agent Helper');
@@ -109,7 +108,7 @@ export async function getAgentEmbodiments(agentID) {
export async function getAgentIdByDomain(domain = '') {
let agentId;
- //first check if this is the internal wildcard agents domain
+ // first check if this is the internal wildcard agents domain
const isStageWildcardDomain = domain.includes(config.env.DEFAULT_AGENT_DOMAIN);
const isProdWildcardDomain = domain.includes(config.env.PROD_AGENT_DOMAIN);
if (isStageWildcardDomain || isProdWildcardDomain) {
@@ -143,7 +142,7 @@ export async function getAgentIdByDomain(domain = '') {
function migrateAgentData(data) {
if (!data.version) {
const newData = JSON.parse(JSON.stringify(data));
- for (let component of newData.components) {
+ for (const component of newData.components) {
component.outputs = component.connectors;
component.inputs = component.receptors;
component.outputProps = component.connectorProps;
diff --git a/packages/runtime/src/core/helpers/logto.helper.ts b/packages/runtime/src/core/helpers/logto.helper.ts
index 006c2c33..37b1c68f 100644
--- a/packages/runtime/src/core/helpers/logto.helper.ts
+++ b/packages/runtime/src/core/helpers/logto.helper.ts
@@ -1,7 +1,7 @@
import axios from 'axios';
import qs from 'querystring';
import config from '../config';
-//M2M test
+// M2M test
const postData = {
grant_type: 'client_credentials',
resource: 'https://default.logto.app/api',
@@ -10,7 +10,7 @@ const postData = {
const base64Credentials = Buffer.from(`${config.env.LOGTO_M2M_APP_ID}:${config.env.LOGTO_M2M_APP_SECRET}`, 'utf8').toString('base64');
-let tokenData = {
+const tokenData = {
access_token: null,
};
export function getM2MToken(resource?, scope?) {
@@ -28,7 +28,7 @@ export function getM2MToken(resource?, scope?) {
method: 'post',
url: `${config.env.LOGTO_SERVER}/oidc/token`,
headers: {
- Authorization: 'Basic ' + base64Credentials,
+ Authorization: `Basic ${base64Credentials}`,
'Content-Type': 'application/x-www-form-urlencoded',
},
data: qs.stringify(body),
@@ -45,4 +45,3 @@ export function getM2MToken(resource?, scope?) {
});
});
}
-
diff --git a/packages/runtime/src/core/middlewares/validate.mw.ts b/packages/runtime/src/core/middlewares/validate.mw.ts
index 55773c98..b9384a68 100644
--- a/packages/runtime/src/core/middlewares/validate.mw.ts
+++ b/packages/runtime/src/core/middlewares/validate.mw.ts
@@ -8,7 +8,7 @@ type AnyObject = {
const pick = (object: AnyObject, keys: string[]) =>
keys.reduce((newObject: AnyObject, key) => {
- if (object && Object.prototype.hasOwnProperty.call(object, key)) {
+ if (object && Object.hasOwn(object, key)) {
// eslint-disable-next-line no-param-reassign
newObject[key] = object[key];
}
diff --git a/packages/runtime/src/core/services/smythAPIReq.ts b/packages/runtime/src/core/services/smythAPIReq.ts
index cde93be5..5bd04f30 100644
--- a/packages/runtime/src/core/services/smythAPIReq.ts
+++ b/packages/runtime/src/core/services/smythAPIReq.ts
@@ -1,7 +1,7 @@
import axios from 'axios';
import config from '../config';
-//middleware sys API
+// middleware sys API
export const mwSysAPI = axios.create({
baseURL: `${config.env.MIDDLEWARE_API_BASE_URL}/_sysapi/v1`,
});
diff --git a/packages/runtime/src/core/utils/general.utils.ts b/packages/runtime/src/core/utils/general.utils.ts
index d12e03dc..93230dbd 100644
--- a/packages/runtime/src/core/utils/general.utils.ts
+++ b/packages/runtime/src/core/utils/general.utils.ts
@@ -4,7 +4,7 @@ export function uid() {
return (Date.now() + Math.random()).toString(36).replace('.', '').toUpperCase();
}
-export const hasKeyTemplateVar = (str: string = ''): boolean => {
+export const hasKeyTemplateVar = (str = ''): boolean => {
if (!str || typeof str !== 'string') return false;
return (str?.match(/{{KEY\((.*?)\)}}/g) ?? []).length > 0;
};
@@ -19,11 +19,9 @@ export function parseTemplate(str, obj, { escapeString = true, processUnmatched
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');
- }
+ } 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
@@ -33,7 +31,7 @@ export function parseTemplate(str, obj, { escapeString = true, processUnmatched
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
+ // 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);
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index 3d6109f2..194fbb12 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -37,7 +37,7 @@ const sre = SmythRuntime.Instance.init({
Storage: {
Connector: 'LocalStorage',
Settings: {
- folder: config.env.DATA_PATH + '/tmp',
+ folder: `${config.env.DATA_PATH}/tmp`,
},
},
Cache: {
@@ -52,7 +52,7 @@ const sre = SmythRuntime.Instance.init({
oAuthBaseUrl: `${config.env.LOGTO_SERVER}/oidc/token`,
oAuthResource: config.env.LOGTO_API_RESOURCE,
oAuthScope: '',
- smythAPIBaseUrl: config.env.MIDDLEWARE_API_BASE_URL + '/_sysapi',
+ smythAPIBaseUrl: `${config.env.MIDDLEWARE_API_BASE_URL}/_sysapi`,
},
},
Vault: {
@@ -81,7 +81,7 @@ const sre = SmythRuntime.Instance.init({
oAuthBaseUrl: `${config.env.LOGTO_SERVER}/oidc/token`,
oAuthResource: config.env.LOGTO_API_RESOURCE,
oAuthScope: '',
- smythAPIBaseUrl: config.env.MIDDLEWARE_API_BASE_URL + '/_sysapi',
+ smythAPIBaseUrl: `${config.env.MIDDLEWARE_API_BASE_URL}/_sysapi`,
},
},
Log: {
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 e80bb13c..30c7e003 100644
--- a/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts
+++ b/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts
@@ -15,7 +15,7 @@ export default async function agentLoader(req, res, next) {
return next();
}
let agentId = req.header('X-AGENT-ID');
- let agentVersion = req.header('X-AGENT-VERSION') || '';
+ const 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 = '';
@@ -49,7 +49,7 @@ export default async function agentLoader(req, res, next) {
isTestDomain = true;
}
if (agentDomain && !isTestDomain && !version) {
- //when using a production domain but no version is specified, use latest
+ // when using a production domain but no version is specified, use latest
version = 'latest';
}
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 417aead4..043036b2 100644
--- a/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts
+++ b/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts
@@ -11,7 +11,7 @@ const router = express.Router();
router.use(agentLoader);
// @ts-ignore
router.get('/authorize', async (req: Request, res: Response) => {
- //@ts-ignore
+ // @ts-ignore
const agent: Agent = req._agent;
if (!agent) {
return res.status(404).json({ error: 'Agent not found' });
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 9201ffb1..58a282ea 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
@@ -8,7 +8,7 @@ export async function processAgentRequest(agent: any, req: Request) {
if (!agent) {
return { status: 404, data: 'Agent not found' };
}
- //const req = agent.agentRequest;
+ // const req = agent.agentRequest;
req.socket.on('close', () => {
// console.log('Client socket closed, killing agent');
@@ -27,9 +27,9 @@ export async function processAgentRequest(agent: any, req: Request) {
async function runAgentProcess(agent: any, req: any) {
try {
- //extract endpoint path
- //live agents (dev) do not have a version number
- //deployed agents have a version number
+ // extract endpoint path
+ // live agents (dev) do not have a version number
+ // 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' } };
diff --git a/packages/runtime/src/modules/debugger/middlewares/agentLoader.mw.ts b/packages/runtime/src/modules/debugger/middlewares/agentLoader.mw.ts
index 25afae11..5c934b67 100644
--- a/packages/runtime/src/modules/debugger/middlewares/agentLoader.mw.ts
+++ b/packages/runtime/src/modules/debugger/middlewares/agentLoader.mw.ts
@@ -13,7 +13,7 @@ export default async function agentLoader(req, res, next) {
return next();
}
let agentId = req.header('X-AGENT-ID');
- let agentVersion = req.header('X-AGENT-VERSION') || '';
+ const 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 =
@@ -53,7 +53,7 @@ export default async function agentLoader(req, res, next) {
isTestDomain = true;
}
if (agentDomain && !isTestDomain && !version && !debugHeader) {
- //when using a production domain but no version is specified, use latest
+ // when using a production domain but no version is specified, use latest
version = 'latest';
}
let agentData;
diff --git a/packages/runtime/src/modules/debugger/middlewares/teamAccessCheck.mw.ts b/packages/runtime/src/modules/debugger/middlewares/teamAccessCheck.mw.ts
index a8634cdb..fac6c19e 100644
--- a/packages/runtime/src/modules/debugger/middlewares/teamAccessCheck.mw.ts
+++ b/packages/runtime/src/modules/debugger/middlewares/teamAccessCheck.mw.ts
@@ -5,7 +5,7 @@ import { mwUserAPI } from '@core/services/smythAPIReq';
const console = Logger('(Debugger) Middleware: Team Access Check');
export async function teamAccessCheck(req, res, next) {
- let teamId = req.params.teamId;
+ const teamId = req.params.teamId;
const accessToken = req.header('Authorization') ? req.header('Authorization').split(' ')[1] : null;
if (!accessToken) {
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 e47d0223..fcce3749 100644
--- a/packages/runtime/src/modules/debugger/services/agent-request-handler.ts
+++ b/packages/runtime/src/modules/debugger/services/agent-request-handler.ts
@@ -8,7 +8,7 @@ import { getMockData } from '@core/helpers/agent.helper';
const console = Logger('Service: Agent Request Handler');
-const debugPromises: any = {}; //TODO : persist this ?
+const debugPromises: any = {}; // TODO : persist this ?
const sseConnections = new Map();
export function getDebugSession(id) {
@@ -60,12 +60,12 @@ export async function processAgentRequest(agentId: string, req: any) {
}
await agentProcess.ready();
- //const req = agent.agentRequest;
+ // const req = agent.agentRequest;
req.socket.on('close', () => {
// console.log('Client socket closed, killing agent');
// Handle the cancellation logic
- //agentProcess.agent.kill();
+ // agentProcess.agent.kill();
});
const skipDebug = typeof req.header('X-DEBUG-SKIP') != 'undefined';
@@ -167,7 +167,7 @@ export async function processAgentRequest(agentId: string, req: any) {
async function runAgentProcess(agentId: string, agentProcess: AgentProcess, req: any) {
try {
- //const req = agent.agentRequest;
+ // const req = agent.agentRequest;
const debugPromiseId = `${agentId}`;
if (req.header('X-DEBUG-STOP')) {
@@ -179,16 +179,16 @@ async function runAgentProcess(agentId: string, agentProcess: AgentProcess, req:
}
}
- //at this point dbgPromise might not exist yet
+ // at this point dbgPromise might not exist yet
let dbgPromise = debugPromises[debugPromiseId];
if (dbgPromise?.sse) {
- //this sse was set by the runAgentDebug() function
- //we need to propagate it in order to capture each execution step stream in the same SSE monitor
+ // this sse was set by the runAgentDebug() function
+ // we need to propagate it in order to capture each execution step stream in the same SSE monitor
agentProcess.agent.addSSE(dbgPromise.sse);
}
- //extract endpoint path
- //live agents (dev) do not have a version number
- //deployed agents have a version number
+ // extract endpoint path
+ // live agents (dev) do not have a version number
+ // 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' } };
@@ -204,31 +204,31 @@ async function runAgentProcess(agentId: string, agentProcess: AgentProcess, req:
url: undefined,
headers: {
...req.headers,
- //'X-DEBUG-RUN': '',
+ // 'X-DEBUG-RUN': '',
},
})
.catch(error => ({ data: { error: error.toString() } }));
if (result.error) {
console.error('ERROR', result.error);
- //res.status(500).json({ ...result, error: result.error.toString(), agentId: agent.id, agentName: agent.name });
+ // res.status(500).json({ ...result, error: result.error.toString(), agentId: agent.id, agentName: agent.name });
return {
status: 500,
data: {
...result,
error: result.error.toString(),
- agentId: agentId,
+ agentId,
// agentName: agent?.name
agentName: undefined,
},
};
}
- //handle API embodiments debug response
+ // handle API embodiments debug response
const dbgSession = result?.dbgSession || result?.expiredDbgSession || '';
dbgPromise = debugPromises[debugPromiseId];
if (dbgSession && dbgPromise) {
if (result.finalResult) {
- //const result = debugPromises[agent.id].result;
+ // 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`,
);
@@ -251,24 +251,23 @@ async function runAgentProcess(agentId: string, agentProcess: AgentProcess, req:
}
async function runAgentDebug(agentId: string, agentProcess: AgentProcess, req: Request) {
try {
- //const req = agent.agentRequest;
+ // const req = agent.agentRequest;
const debugPromiseId = `${agentId}`;
const excludedHeaders = ['host', 'content-length', 'accept-encoding'];
const headers = Object.keys(req.headers)
.filter(header => !excludedHeaders.includes(header.toLowerCase()))
.reduce((obj, header) => {
- obj[header] = req.headers[header];
- return obj;
+ return { ...obj, [header]: req.headers[header] };
}, {});
headers['X-AGENT-ID'] = agentId;
headers['X-DEBUG-RUN'] = '';
- //'X-DEBUG-RUN': '',
+ // 'X-DEBUG-RUN': '',
const port = config.env.PORT;
- let url = `http://localhost:${port}${req.path.replace('/debug', '/api')}`;
- //add query params
+ const 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) {
const query = Object.keys(req.query)
@@ -279,27 +278,29 @@ async function runAgentDebug(agentId: string, agentProcess: AgentProcess, req: R
const input = req.method == 'GET' ? req.query : req.body;
- //check if request has form-data
+ // check if request has form-data
- //the following line does not handle get request case
- //const apiResponse = await axios.post(url, input, { headers }); //call the actual agentAPI locally
+ // the following line does not handle get request case
+ // const apiResponse = await axios.post(url, input, { headers }); //call the actual agentAPI locally
let apiResponse;
- //make sure to map binary data back to the request body that we'll send to the agent
+ // make sure to map binary data back to the request body that we'll send to the agent
// @ts-ignore
if (req.files) {
- //send request with formData
+ // send request with formData
const formData = new FormData();
- //@ts-ignore
- for (let file of req.files) {
+ // @ts-ignore
+ for (const file of req.files) {
const fieldname = file.fieldname;
- //get blob from file.buffer
+ // get blob from file.buffer
const blob = new Blob([file.buffer], { type: file.mimetype });
formData.append(fieldname, blob, file.originalname);
}
- for (let entry in req.body) {
- formData.append(entry, req.body[entry]);
+ for (const entry in req.body) {
+ if (Object.hasOwn(req.body, entry)) {
+ formData.append(entry, req.body[entry]);
+ }
}
apiResponse = await axios({
@@ -310,7 +311,7 @@ async function runAgentDebug(agentId: string, agentProcess: AgentProcess, req: R
params: req.query,
});
} else {
- //send request with json body
+ // send request with json body
apiResponse = await axios({
method: req.method,
url,
@@ -319,10 +320,10 @@ async function runAgentDebug(agentId: string, agentProcess: AgentProcess, req: R
params: req.query,
});
}
- //const apiAgentResponse = await runAgentProcess(agent); //TODO : refactor the internal logic to use runAgentProcess() instead of making a post request
+ // const apiAgentResponse = await runAgentProcess(agent); //TODO : refactor the internal logic to use runAgentProcess() instead of making a post request
const dbgSession = apiResponse?.data?.dbgSession;
if (dbgSession) {
- //const agentId = agent.id;
+ // 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`,
@@ -350,12 +351,12 @@ async function runAgentDebug(agentId: string, agentProcess: AgentProcess, req: R
reject,
sse: agentProcess.agent.sse,
};
- //promise expiration
+ // promise expiration
setTimeout(
() => {
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(new Error('Debug Session Expired'));
},
60 * 60 * 1000, // 1 hour
);
@@ -374,11 +375,11 @@ async function runAgentDebug(agentId: string, agentProcess: AgentProcess, req: R
};
}
- let data = finalResult;
+ const data = finalResult;
return { status: 200, data };
}
- //res.status(apiResponse.status).send(apiResponse.data);
+ // res.status(apiResponse.status).send(apiResponse.data);
} catch (error: any) {
if (error.response) {
// The request was made, but the server responded with a non-2xx status
diff --git a/packages/runtime/src/modules/embodiment/helpers/chatgpt.helper.ts b/packages/runtime/src/modules/embodiment/helpers/chatgpt.helper.ts
index a45f530b..cc638eed 100644
--- a/packages/runtime/src/modules/embodiment/helpers/chatgpt.helper.ts
+++ b/packages/runtime/src/modules/embodiment/helpers/chatgpt.helper.ts
@@ -1,13 +1,15 @@
import fs from 'fs';
import path from 'path';
-import { JSONContentHelper, TemplateStringHelper } from '@smythos/sre';
+import { JSONContentHelper, Logger, TemplateStringHelper } from '@smythos/sre';
import { getAgentDataById, getAgentEmbodiments, getAgentIdByDomain } from '@core/helpers/agent.helper';
import { EMBODIMENT_TYPES } from '@embodiment/constants';
import { ChatGPTManifest } from '@embodiment/types/chatgpt.types';
+const console = Logger('[Embodiment] Helper: ChatGPT');
+
let chatGPTDataPath = './data/chatGPT';
// Path to data files differs between server ('./data/chatGPT') and tests ('../data/chatGPT').
@@ -16,13 +18,13 @@ if (process.env.TEST_ENV) {
}
// a function that splits a string on a word boundary not exceeding a max characters length
-function splitOnSeparator(str = '', maxLen, separator = ' .') {
+function splitOnSeparator(maxLen: number, str = '', separator = ' .') {
if (str.length <= maxLen) {
return str;
}
// Find the last occurrence of the separator before maxLen
- let idx = str.lastIndexOf(separator, maxLen);
+ const idx = str.lastIndexOf(separator, maxLen);
// If the separator is not found, return the substring up to maxLen
if (idx === -1) {
@@ -33,7 +35,7 @@ function splitOnSeparator(str = '', maxLen, separator = ' .') {
return str.substring(0, idx);
}
-//FIXME load version from prod domain
+// FIXME load version from prod domain
async function getChatGPTManifestById(agentId: string, domain: string, version: string): Promise<ChatGPTManifest> {
console.log('getChatGPTManifestById', agentId, domain, version);
if (!agentId) {
@@ -63,17 +65,17 @@ async function getChatGPTManifestById(agentId: string, domain: string, version:
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
+ // 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 || '',
120,
+ _chatgptHumanDescription || agentData.data.shortDescription || agentData.data.description || '',
'.',
);
- const description = splitOnSeparator(_chatgptDesctiption || agentData.data.behavior || agentData.data.description || '', 8000, '.');
+ const description = splitOnSeparator(8000, _chatgptDesctiption || agentData.data.behavior || agentData.data.description || '', '.');
- 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 iconUrl = chatgptEmbodiment?.properties?.logoUrl || 'https://proxy-02.api.smyth.ai/static/img/icon.svg';
+ const contactEmail = _contactEmail || '';
+ const legalInfoUrl = _legalInfoUrl || '';
const aiPluginTemplate = fs.readFileSync(path.resolve(__dirname, `${chatGPTDataPath}/ai-plugin.tpl.json`), 'utf8');
@@ -82,9 +84,9 @@ async function getChatGPTManifestById(agentId: string, domain: string, version:
model_name: modelName,
human_description: humanDescription,
model_description: description,
- icon_url,
- contact_email,
- legal_info_url,
+ icon_url: iconUrl,
+ contact_email: contactEmail,
+ legal_info_url: legalInfoUrl,
domain,
}).result;
const parsedManifest = JSONContentHelper.create(manifest).tryParse();
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 29a5cf38..7521d1ee 100644
--- a/packages/runtime/src/modules/embodiment/helpers/openapi-adapter.helper.ts
+++ b/packages/runtime/src/modules/embodiment/helpers/openapi-adapter.helper.ts
@@ -60,13 +60,13 @@ const agentDataConnector = new EmbodimentAgentDataConnector();
* Constructs the server URL from domain using environment configuration
*/
function constructServerUrl(domain: string): string {
- const server_url_scheme =
+ const serverUrlScheme =
config.env.NODE_ENV === 'development' && config.env.AGENT_DOMAIN_PORT && domain.includes(config.env.DEFAULT_AGENT_DOMAIN) ? 'http' : 'https';
- const server_url_port =
+ const serverUrlPort =
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}`;
+ return `${serverUrlScheme}://${domain}${serverUrlPort}`;
}
/**
@@ -78,9 +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> {
- const server_url = constructServerUrl(domain);
- const result = await agentDataConnector.getOpenAPIJSON(agent, server_url, version, aiOnly);
+export async function getOpenAPIJSON(agent: any, domain: string, version: string, aiOnly = false): Promise<OpenAPISpec> {
+ const serverUrl = constructServerUrl(domain);
+ const result = await agentDataConnector.getOpenAPIJSON(agent, serverUrl, version, aiOnly);
return result;
}
@@ -98,8 +98,8 @@ async function getOpenAPIJSONById(
agentId: string,
domain: string,
version: string,
- aiOnly: boolean = false,
- addDefaultFileParsingAgent: boolean = false,
+ aiOnly = false,
+ addDefaultFileParsingAgent = false,
): Promise<any> {
try {
if (!agentId) {
@@ -121,8 +121,8 @@ async function getOpenAPIJSONById(
addDefaultComponentsAndConnections(agentData);
}
- const server_url = constructServerUrl(domain);
- const result = await agentDataConnector.getOpenAPIJSON(agentData, server_url, version, aiOnly);
+ const serverUrl = constructServerUrl(domain);
+ const result = await agentDataConnector.getOpenAPIJSON(agentData, serverUrl, version, aiOnly);
return result;
} catch (error) {
return { error: error.message || 'OpenAPI generation failed' };
@@ -137,7 +137,7 @@ 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 = false): Promise<any> {
try {
const agentId = await getAgentIdByDomain(domain);
if (!agentId) {
diff --git a/packages/runtime/src/modules/embodiment/middlewares/ChatbotLoader.mw.ts b/packages/runtime/src/modules/embodiment/middlewares/ChatbotLoader.mw.ts
index cf7167a7..24971520 100644
--- a/packages/runtime/src/modules/embodiment/middlewares/ChatbotLoader.mw.ts
+++ b/packages/runtime/src/modules/embodiment/middlewares/ChatbotLoader.mw.ts
@@ -1,16 +1,20 @@
-import { Agent } from '@smythos/sre';
+import { Agent, Logger } from '@smythos/sre';
+
import Chatbot from '../services/Chatbot.class';
import ApiError from '../utils/apiError';
-//TODO : handle cache TTL
-const __chatbot_cache = { 0: 1 };
+const console = Logger('[Embodiment] Middleware: Chatbot Loader');
+
+// TODO : handle cache TTL
+
+const chatbotCache = { 0: 1 };
export default async function ChatbotLoader(req, res, next) {
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 (chatbotCache[agent.id] && !agent.usingTestDomain) {
+ const chatBotData = chatbotCache[agent.id];
if (chatBotData.agentVersion == agent.version) {
console.log(`Chatbot loaded from cache, domain=${chatBotData.domain} version=${chatBotData.version}`);
const chatbot = new Chatbot(req);
@@ -23,7 +27,7 @@ export default async function ChatbotLoader(req, res, next) {
req._chatbot = chatbot;
await req._chatbot.init();
- __chatbot_cache[agent.id] = chatbot.serialize(); //we cannot store an object in session, so we serialize it
+ chatbotCache[agent.id] = chatbot.serialize(); // we cannot store an object in session, so we serialize it
}
} catch (error) {
if (error.errKey == 'MODEL_NOT_SUPPORTED') {
diff --git a/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts b/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts
index 093537a6..de9457e9 100644
--- a/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts
+++ b/packages/runtime/src/modules/embodiment/middlewares/agentLoader.mw.ts
@@ -9,14 +9,14 @@ export default async function agentLoader(req, res, next) {
console.log('agentLoader', req.path);
const agentDataConnector = ConnectorService.getAgentDataConnector();
- const isAgentLLMCall = req.body.model ? true : false;
+ const isAgentLLMCall = !!req.body.model;
const agentFromModel: any = isAgentLLMCall ? getAgentIdAndVersion(req.body.model) : {};
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 agentVersion = req.header('X-AGENT-VERSION') || agentFromModel.version || '';
const isAgentChatRequest = req.header('x-conversation-id') !== undefined;
const debugHeader =
req.header('X-DEBUG-STOP') !== undefined ||
@@ -55,7 +55,7 @@ export default async function agentLoader(req, res, next) {
isTestDomain = true;
}
if (agentDomain && !isTestDomain && !version) {
- //when using a production domain but no version is specified, use latest
+ // when using a production domain but no version is specified, use latest
version = 'latest';
}
let agentData;
@@ -92,7 +92,7 @@ export default async function agentLoader(req, res, next) {
req.socket.on('close', () => {
// console.log('Client socket closed, killing agent');
// Handle the cancellation logic
- //req._agent.kill();
+ // req._agent.kill();
});
// req._agent.auth is empty for sre-embodiment-server; the actual auth data exists in agentData.data.auth or req._agent.data.auth
// However, the auth middleware in the sre-agent-server project expects auth data in req._agent.auth,
@@ -108,7 +108,7 @@ export default async function agentLoader(req, res, next) {
req._agent.domain = isAgentLLMCall ? 'AgentLLM' : agentDomain || (await getAgentDomainById(agentId));
// req._agent.version = version;
req._agentVersion = version;
- //req._data1 = 1;
+ // req._data1 = 1;
console.log(`Loaded Agent:${agentId} v=${version} path=${path} isTestDomain=${isTestDomain} domain=${agentDomain}`);
return next();
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 833d5de8..fb3c91a3 100644
--- a/packages/runtime/src/modules/embodiment/modules/API/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/API/routes/router.ts
@@ -8,10 +8,10 @@ const router = express.Router();
const openapiJSONHandler = async (req, res) => {
const agent: Agent = req._agent;
- let domain = req.hostname;
+ const domain = req.hostname;
// const debugSessionEnabled = agent.debugSessionEnabled;
// const isTestDomain = agent.usingTestDomain;
- //FIXME : use the right version depending on domain [FIXED]
+ // 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 => {
@@ -22,16 +22,16 @@ const openapiJSONHandler = async (req, res) => {
if (openAPIObj?.error) {
return res.status(500).send({ error: openAPIObj.error });
}
- //set application type to json
+ // set application type to json
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(openAPIObj, null, 2));
};
const openapiJSON4LLMHandler = async (req, res) => {
- let domain = req.hostname;
+ const domain = req.hostname;
// const debugSessionEnabled = agent.debugSessionEnabled;
// const isTestDomain = agent.usingTestDomain;
- //FIXME : use the right version depending on domain [FIXED]
+ // 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 => {
@@ -42,14 +42,14 @@ const openapiJSON4LLMHandler = async (req, res) => {
if (openAPIObj?.error) {
return res.status(500).send({ error: openAPIObj.error });
}
- //set application type to json
+ // set application type to 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);
-//legacy
+// legacy
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 17566fc1..5efebd1c 100644
--- a/packages/runtime/src/modules/embodiment/modules/agentChat/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/agentChat/routes/router.ts
@@ -1,6 +1,8 @@
import express from 'express';
import Joi from 'joi';
+import { Logger } from '@smythos/sre';
+
import config from '@core/config';
import { getM2MToken } from '@core/helpers/logto.helper';
import UserAgentAccessCheck from '@core/middlewares/userAgentAccessCheck.mw';
@@ -13,6 +15,8 @@ import ChatbotLoader from '@embodiment/middlewares/ChatbotLoader.mw';
import Chatbot from '@embodiment/services/Chatbot.class';
import { buildConversationId } from '@embodiment/utils/chat.utils';
+const console = Logger('[Embodiment] Router: Agent Chat');
+
// Import ChatbotResponse type for proper typing
type ChatbotResponse = {
content?: string;
@@ -32,8 +36,8 @@ const router = express.Router();
const middlewares = [UserAgentAccessCheck, agentLoader, ChatbotLoader];
router.use(middlewares);
-let localAgentAuthorizations = {
- //FIXME : this seems like a hardcoded value used by Arslan during implementation, should we remove it ?
+const localAgentAuthorizations = {
+ // FIXME : this seems like a hardcoded value used by Arslan during implementation, should we remove it ?
clzi8yw441kcfblqz6zj9bv1h: {
verifiedKey: 'SomeRandomToken',
authMethod: 'api-key-bearer',
@@ -81,7 +85,7 @@ router.post('/stream', async (req, res) => {
const headers: any = {};
if (verifiedKey) {
- headers['Authorization'] = `Bearer ${verifiedKey}`;
+ headers.Authorization = `Bearer ${verifiedKey}`;
}
console.log('headers', {
@@ -96,12 +100,11 @@ router.post('/stream', async (req, res) => {
return res.status(500).send({ error: 'Data path is not set' });
}
- //set response headers
+ // set response headers
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;
@@ -143,7 +146,7 @@ router.post('/stream', 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 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' });
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 3b736ecd..436ff7be 100644
--- a/packages/runtime/src/modules/embodiment/modules/alexa/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/alexa/routes/router.ts
@@ -6,6 +6,7 @@ import { DEFAULT_AGENT_MODEL_SETTINGS_KEY, DEFAULT_MODEL } from '@core/constants
import agentLoader from '@embodiment/middlewares/agentLoader.mw';
import { createAlexaSkill, handleAlexaRequest, isAlexaEnabled, parseAlexaRequest } from '../services/alexa.service';
+
const router = express.Router();
router.post('/', agentLoader, async (req: any, res) => {
@@ -33,10 +34,10 @@ router.post('/publish', agentLoader, async (req: any, res) => {
const agent: Agent = req._agent;
const agentName = agent.name;
const agentDomain = agent.domain;
- let accessToken = req.body.accessToken;
- let vendorId = req.body.vendorId;
+ const accessToken = req.body.accessToken;
+ const vendorId = req.body.vendorId;
const scheme = agentDomain.includes(':') ? 'http' : 'https';
- let endpoint = `${scheme}://${agentDomain}/alexa`;
+ const endpoint = `${scheme}://${agentDomain}/alexa`;
await createAlexaSkill(agentName, accessToken, vendorId, endpoint);
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 be1a6140..9762f4c8 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,6 +1,7 @@
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';
@@ -83,7 +84,7 @@ function buildAlexaResponse(outputSpeech: string, reprompt = '', shouldEndSessio
text: reprompt,
},
},
- shouldEndSession: shouldEndSession,
+ shouldEndSession,
},
};
}
@@ -94,11 +95,11 @@ export async function createAlexaSkill(agentName: string, accessToken: string, v
method: 'post',
url: `${ALEXA_BASE_URL}/v1/skills`,
headers: {
- Authorization: 'Bearer ' + accessToken,
+ Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
data: {
- vendorId: vendorId,
+ vendorId,
manifest: {
apis: {
custom: {
@@ -116,10 +117,10 @@ export async function createAlexaSkill(agentName: string, accessToken: string, v
locales: {
'en-US': {
description: 'Smythos agent',
- examplePhrases: ['Alexa open ' + agentName],
+ examplePhrases: [`Alexa open ${agentName}`],
keywords: [agentName],
name: agentName,
- summary: 'invoke ' + agentName,
+ summary: `invoke ${agentName}`,
},
},
},
@@ -133,7 +134,7 @@ export async function createAlexaSkill(agentName: string, accessToken: string, v
method: 'put',
url: `${ALEXA_BASE_URL}/v1/skills/${skillId}/stages/development/interactionModel/locales/en-US`,
headers: {
- Authorization: 'Bearer ' + accessToken,
+ Authorization: `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
data: {
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 80a6c713..2e069894 100644
--- a/packages/runtime/src/modules/embodiment/modules/chatGPT/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/chatGPT/routes/router.ts
@@ -1,12 +1,17 @@
+import express from 'express';
+
+import { Logger } from '@smythos/sre';
+
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 console = Logger('[Embodiment] Router: ChatGPT');
const router = express.Router();
router.get('/.well-known/ai-plugin.json', agentLoader, async (req: any, res) => {
- let domain = req.hostname;
+ const domain = req.hostname;
const manifest = await getChatGPTManifest(req._rawAgent, domain).catch(error => {
console.error(error);
@@ -17,14 +22,14 @@ router.get('/.well-known/ai-plugin.json', agentLoader, async (req: any, res) =>
return res.status(500).send({ error: manifest.error });
}
- console.log(`Manifest requested from domain ${domain} = ` + JSON.stringify(manifest, null, 2));
+ 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);
+ // res.json(manifest);
});
router.get('/api-docs/openapi-gpt.json', agentLoader, async (req: any, res) => {
- let domain = req.hostname;
+ const domain = req.hostname;
const openAPIObj = await getOpenAPIJSON(req._rawAgent, domain, req._agentVersion, true).catch(error => {
console.error(error);
@@ -38,20 +43,24 @@ router.get('/api-docs/openapi-gpt.json', agentLoader, async (req: any, res) => {
// Transform from 3.0.1 to 3.1.0 format for GPT compatibility
const transformedSpec = transformOpenAPI301to310(openAPIObj);
- //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
+ // 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) {
- 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, '.');
+ for (const path in transformedSpec.paths) {
+ if (Object.hasOwn(transformedSpec.paths, path)) {
+ const entry = transformedSpec.paths[path];
+ for (const method in entry) {
+ if (Object.hasOwn(entry, method)) {
+ if (!entry[method].summary) continue;
+ // * Improvement: Instead of truncating the summary, we can rephrase it using an LLM.
+ entry[method].summary = splitOnSeparator(300, entry[method].summary, '.');
+ }
+ }
}
}
}
- //set application type to json
+ // set application type to json
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify(transformedSpec, null, 2));
});
@@ -84,56 +93,59 @@ function transformOpenAPI301to310(spec: any): any {
function transformSchema(schema: any): any {
if (!schema || typeof schema !== 'object') return schema;
+ // Create a copy to avoid mutating the parameter
+ const schemaCopy = { ...schema };
+
// Handle array schemas - ensure items is properly defined
- if (schema.type === 'array') {
- if (!schema.items || Object.keys(schema.items).length === 0) {
- schema.items = { type: 'string' }; // Default to string items
+ if (schemaCopy.type === 'array') {
+ if (!schemaCopy.items || Object.keys(schemaCopy.items).length === 0) {
+ schemaCopy.items = { type: 'string' }; // Default to string items
} else {
- schema.items = transformSchema(schema.items);
+ schemaCopy.items = transformSchema(schemaCopy.items);
}
}
// Handle object schemas - fix empty additionalProperties
- if (schema.type === 'object') {
+ if (schemaCopy.type === 'object') {
if (
- schema.additionalProperties !== undefined &&
- typeof schema.additionalProperties === 'object' &&
- Object.keys(schema.additionalProperties).length === 0
+ schemaCopy.additionalProperties !== undefined &&
+ typeof schemaCopy.additionalProperties === 'object' &&
+ Object.keys(schemaCopy.additionalProperties).length === 0
) {
- schema.additionalProperties = true; // Allow any additional properties
+ schemaCopy.additionalProperties = true; // Allow any additional properties
}
// Transform nested properties
- if (schema.properties) {
- for (const [key, prop] of Object.entries(schema.properties)) {
- schema.properties[key] = transformSchema(prop);
+ if (schemaCopy.properties) {
+ for (const [key, prop] of Object.entries(schemaCopy.properties)) {
+ schemaCopy.properties[key] = transformSchema(prop);
}
}
}
// Handle binary format - convert to string with contentEncoding
- if (schema.format === 'binary') {
- delete schema.format;
- schema.type = 'string';
- schema.contentEncoding = 'base64';
+ if (schemaCopy.format === 'binary') {
+ delete schemaCopy.format;
+ schemaCopy.type = 'string';
+ schemaCopy.contentEncoding = 'base64';
}
// Handle nullable fields (3.0.1 -> 3.1.0)
- if (schema.nullable === true) {
- delete schema.nullable;
+ if (schemaCopy.nullable === true) {
+ delete schemaCopy.nullable;
// Convert to union type with null
- if (schema.type) {
- schema.type = Array.isArray(schema.type) ? [...schema.type, 'null'] : [schema.type, 'null'];
+ if (schemaCopy.type) {
+ schemaCopy.type = Array.isArray(schemaCopy.type) ? [...schemaCopy.type, 'null'] : [schemaCopy.type, 'null'];
}
}
// Recursively transform nested schemas
- if (schema.allOf) schema.allOf = schema.allOf.map(transformSchema);
- if (schema.oneOf) schema.oneOf = schema.oneOf.map(transformSchema);
- if (schema.anyOf) schema.anyOf = schema.anyOf.map(transformSchema);
- if (schema.not) schema.not = transformSchema(schema.not);
+ if (schemaCopy.allOf) schemaCopy.allOf = schemaCopy.allOf.map(transformSchema);
+ if (schemaCopy.oneOf) schemaCopy.oneOf = schemaCopy.oneOf.map(transformSchema);
+ if (schemaCopy.anyOf) schemaCopy.anyOf = schemaCopy.anyOf.map(transformSchema);
+ if (schemaCopy.not) schemaCopy.not = transformSchema(schemaCopy.not);
- return schema;
+ return schemaCopy;
}
// Transform request/response schemas in paths
@@ -170,7 +182,7 @@ function transformOpenAPI301to310(spec: any): any {
if (op.parameters) {
op.parameters = op.parameters.map((param: any) => {
if (param.schema) {
- param.schema = transformSchema(param.schema);
+ return { ...param, schema: transformSchema(param.schema) };
}
return param;
});
@@ -189,13 +201,13 @@ function transformOpenAPI301to310(spec: any): any {
return transformed;
}
-function splitOnSeparator(str = '', maxLen: number, separator = ' .') {
+function splitOnSeparator(maxLen: number, str = '', separator = ' .') {
if (str.length <= maxLen) {
return str;
}
// Find the last occurrence of the separator before maxLen
- let idx = str.lastIndexOf(separator, maxLen);
+ const idx = str.lastIndexOf(separator, maxLen);
// If the separator is not found, return the substring up to maxLen
if (idx === -1) {
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 ca56f121..e8945e09 100644
--- a/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts
@@ -1,11 +1,11 @@
import axios from 'axios';
import express from 'express';
-import { AccessCandidate, Agent, BinaryInput } from '@smythos/sre';
-import { uploadHandler } from '@core/middlewares/uploadHandler.mw';
+import { AccessCandidate, Agent, BinaryInput, Logger } from '@smythos/sre';
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';
@@ -13,6 +13,8 @@ import agentLoader from '@embodiment/middlewares/agentLoader.mw';
import ChatbotLoader from '@embodiment/middlewares/ChatbotLoader.mw';
import { buildConversationId } from '@embodiment/utils/chat.utils';
+const console = Logger('[Embodiment] Router: Chatbot');
+
// Import ChatbotResponse type for proper typing
type ChatbotResponse = {
content?: string;
@@ -36,7 +38,7 @@ router.use(middleweares);
router.get('/', async (req, res) => {
const agent: Agent = req._agent;
- //FIXME : using name as intro message his as a workaround
+ // FIXME : using name as intro message his as a workaround
const name = agent.name;
const debugSessionEnabled = agent.debugSessionEnabled;
const isTestDomain = agent.usingTestDomain;
@@ -44,9 +46,9 @@ 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;
+ 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
+ // 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';
@@ -95,7 +97,7 @@ router.get('/chat-configs', async (req: any, res) => {
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;
});
@@ -128,7 +130,8 @@ router.post('/chat-stream', async (req, res) => {
const abortController = new AbortController();
try {
- let { message, attachments = [] } = req.body;
+ let { message } = req.body;
+ const { attachments = [] } = req.body;
if (attachments.length > 0) {
message = [message, '###', 'Attachments:', ...attachments.map(attachment => `- ${attachment.url}`)].join('\n');
}
@@ -141,9 +144,9 @@ router.post('/chat-stream', async (req, res) => {
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
+ // 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: any = isDebugSession
? {
'X-DEBUG': true,
'X-AGENT-ID': agentId,
@@ -159,7 +162,7 @@ router.post('/chat-stream', async (req, res) => {
'x-conversation-id': chatbot.conversationID,
};
if (verifiedKey) {
- headers['Authorization'] = `Bearer ${verifiedKey}`;
+ headers.Authorization = `Bearer ${verifiedKey}`;
}
// Set up an event listener for client disconnection
@@ -167,7 +170,7 @@ router.post('/chat-stream', async (req, res) => {
abortController.abort();
});
- //set response headers
+ // set response headers
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
@@ -213,13 +216,13 @@ router.get('/params', async (req, res) => {
const agent: Agent = req._agent;
- let sessionData = req.session;
+ const sessionData = req.session;
// wait for agent settings and embodiments to be ready
// await agent.agentSettings?.ready();
// await agent.agentSettings?.embodiments?.ready();
- let promises = [agent.agentSettings?.ready(), agent.agentSettings?.embodiments?.ready()];
+ const promises = [agent.agentSettings?.ready(), agent.agentSettings?.embodiments?.ready()];
let authInfo;
@@ -279,8 +282,8 @@ router.get('/params', async (req, res) => {
authRequired: isAuthRequired(),
auth: {
method: authInfo?.method,
- redirectUri: redirectUri,
- authorizationUrl: authorizationUrl,
+ redirectUri,
+ authorizationUrl,
clientID: authInfo?.provider?.clientID,
redirectInternalEndpoint: '/chatbot/callback',
},
@@ -317,7 +320,7 @@ function setSessionToken(req: any, res: any, token: string, authMethod: string)
}
req.session.agentAuthorizations[agentId] = {
verifiedKey: token,
- authMethod: authMethod,
+ authMethod,
};
req.session.save(err => {
if (err) {
@@ -334,7 +337,7 @@ function handleLocalAgent(req: any, token: string, authMethod: string) {
}
localAgentAuthorizations[agentId] = {
verifiedKey: token,
- authMethod: authMethod,
+ authMethod,
};
}
}
@@ -353,7 +356,7 @@ async function handleOAuthCallback(req: any, res: any) {
async function getAuthInfo(req: any) {
if (req._agent?.data?.auth) {
- return await readAgentOAuthConfig(req._agent.data);
+ return readAgentOAuthConfig(req._agent.data);
}
return null;
}
@@ -426,6 +429,7 @@ router.post('/verify-chat-key', async (req: any, res) => {
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 });
}
});
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 e787621e..a15d9d47 100644
--- a/packages/runtime/src/modules/embodiment/modules/formPreview/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/formPreview/routes/router.ts
@@ -37,7 +37,7 @@ router.get('/', async (req, res) => {
router.get('/params', async (req, res) => {
const agent: Agent = req._agent;
- let promises = [agent.agentSettings?.ready()];
+ const promises = [agent.agentSettings?.ready()];
await Promise.all(promises);
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 34d025fd..f40ff803 100644
--- a/packages/runtime/src/modules/embodiment/modules/mcp/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/mcp/routes/router.ts
@@ -1,14 +1,14 @@
import express from 'express';
import agentLoader from '@embodiment/middlewares/agentLoader.mw';
-import { Agent } from '@smythos/sre';
+import { Agent, AgentProcess } 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;
+// let transport: SSEServerTransport;
const clientTransports = new Map<string, { transport: SSEServerTransport; server: Server }>();
router.get('/sse', agentLoader, async (req: any, res) => {
@@ -74,7 +74,7 @@ router.get('/sse', agentLoader, async (req: any, res) => {
description: operation.summary || `Endpoint that handles ${method.toUpperCase()} requests to ${endpoint}. ` + `${schema?.description || ''}`,
inputSchema: {
type: 'object',
- properties: properties,
+ properties,
required: schema?.required || [],
},
};
@@ -114,8 +114,8 @@ router.get('/sse', agentLoader, async (req: any, res) => {
// Process the request through the agent
const result = await AgentProcess.load(agent.data).run({
- method: method,
- path: path,
+ method,
+ path,
body: args,
});
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 efd2161c..33869f26 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,4 +1,5 @@
import { Agent } from '@smythos/sre';
+
const MCP_SETTINGS_KEY = 'mcp';
export const isMcpEnabled = (agent: Agent) => {
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 88adc3fb..a2128f95 100644
--- a/packages/runtime/src/modules/embodiment/modules/openai/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/openai/routes/router.ts
@@ -9,6 +9,7 @@ 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');
@@ -35,7 +36,7 @@ router.post('/v1/chat/completions', agentLoader, validate(chatValidations.chatCo
const model = agent.agentSettings?.get(DEFAULT_AGENT_MODEL_SETTINGS_KEY) || DEFAULT_MODEL;
- const authHeader = req.headers['authorization'];
+ const authHeader = req.headers.authorization;
const apiKey = extractBearerToken(authHeader);
const result = await chatService.chatCompletion({
@@ -57,7 +58,7 @@ router.post('/v1/chat/completions', agentLoader, validate(chatValidations.chatCo
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
- let headersSent = false;
+ const headersSent = false;
result.on('error', (error: any) => {
console.warn('Chat completion error:', error);
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 15db3553..83ec852e 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
@@ -99,7 +99,7 @@ class OpenAIChatService {
readable.push(`data: ${JSON.stringify(preparedContent)}\n\n`);
});
- //Removed : passthrough content is now returned as normal content in the content event
+ // Removed : passthrough content is now returned as normal content in the content event
// conv.on('agentCallback', (content) => {
// const now = Date.now();
// const preparedContent: OpenAI.Chat.Completions.ChatCompletionChunk = {
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 014a0ce0..c40b531b 100644
--- a/packages/runtime/src/modules/embodiment/modules/postman/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/postman/routes/router.ts
@@ -6,7 +6,7 @@ import Converter from 'openapi-to-postmanv2';
const router = express.Router();
router.get('/', agentLoader, async (req: any, res) => {
- let domain = req.hostname;
+ const domain = req.hostname;
try {
const openAPISpec = await getOpenAPIJSON(req._rawAgent, domain, req._agentVersion, false).catch(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 460541f9..0a50b065 100644
--- a/packages/runtime/src/modules/embodiment/modules/swagger/routes/router.ts
+++ b/packages/runtime/src/modules/embodiment/modules/swagger/routes/router.ts
@@ -11,9 +11,9 @@ const router = express.Router();
// router.use(swaggerUi.serve);
router.use('/', agentLoader, async (req: any, res) => {
- //TODO : handle release switch : dev, prod, prod old versions [DONE]
+ // TODO : handle release switch : dev, prod, prod old versions [DONE]
const agent: Agent = req._agent;
- let domain = req.hostname;
+ const domain = req.hostname;
// const debugSessionEnabled = agent.debugSessionEnabled;
const isTestDomain = agent.usingTestDomain;
// FIXME : use the right version depending on domain [FIXED]
@@ -45,7 +45,7 @@ initDebug('${config.env.UI_SERVER}', '${agent.id}');
`;
}
- //inject the debug script before closing body tag
+ // inject the debug script before closing body tag
htmlContent = htmlContent.replace('</body>', `${debugScript}</body>`);
res.send(htmlContent);
});
diff --git a/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts b/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts
index 945b9303..29eb031e 100644
--- a/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts
+++ b/packages/runtime/src/modules/embodiment/services/Chatbot.class.ts
@@ -30,12 +30,14 @@ type ChatbotResponse = {
errorType?: string;
};
-function fnv1aHash(str) {
+function fnv1aHash(str: string): string {
let hash = 0x811c9dc5; // FNV offset basis
for (let i = 0; i < str.length; i++) {
+ // eslint-disable-next-line no-bitwise
hash ^= str.charCodeAt(i);
hash = Math.imul(hash, 0x01000193); // FNV prime
}
+ // eslint-disable-next-line no-bitwise
return (hash >>> 0).toString(36).toUpperCase(); // Convert to Base36
}
export default class Chatbot {
@@ -60,10 +62,10 @@ export default class Chatbot {
private isAgentChat = false;
constructor(req: Request | any) {
- this.agentId = req._agent.id; //from AgentLoader middleware
+ this.agentId = req._agent.id; // from AgentLoader middleware
this.sessionID = req.sessionID;
this.conversationID = req.headers['x-conversation-id'] || req.sessionID;
- this.domain = req._agent.domain; //req.hostname;
+ this.domain = req._agent.domain; // req.hostname;
this.agent = req._agent;
this.client_ip = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
this.teamId = req._agent.teamId;
@@ -92,7 +94,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);
}
/**
@@ -105,8 +107,8 @@ export default class Chatbot {
domain: this.domain,
function_call_order: this.function_call_order,
agentVersion: this.agent.version,
- //sessionID: this.sessionID,
- //conversationID: this.conversationID,
+ // sessionID: this.sessionID,
+ // conversationID: this.conversationID,
embodimentSettings: this.embodimentSettings,
systemMessage: this.systemMessage,
model: this.model,
@@ -124,8 +126,8 @@ export default class Chatbot {
this.agentId = data.agentId;
this.domain = data.domain;
this.function_call_order = data.function_call_order;
- //this.sessionID = data.sessionID;
- //this.conversationID = data.conversationID;
+ // this.sessionID = data.sessionID;
+ // this.conversationID = data.conversationID;
this.embodimentSettings = data.embodimentSettings;
this.systemMessage = data.systemMessage;
this.model = data.model;
@@ -146,7 +148,7 @@ export default class Chatbot {
callback({
content: errorMessage,
isError: true,
- errorType: errorType,
+ errorType,
});
}
@@ -178,7 +180,7 @@ export default class Chatbot {
sessionID: conversationID,
});
- this.toolCallId = Math.round(Math.random() * Math.pow(10, 6))
+ this.toolCallId = Math.round(Math.random() * 10 ** 6)
.toString(36)
.toUpperCase();
@@ -194,7 +196,7 @@ export default class Chatbot {
});
conversation.on('error', error => {
- console.error('Error in conversation:', error);
+ // console.error('Error in conversation:', error);
// Send error as normal content with error flag instead of throwing
this.sendErrorMessage(error, 'conversation_error', callback);
@@ -221,13 +223,14 @@ export default class Chatbot {
conversation.on('content', content => {
try {
- if (content?.indexOf('}{') >= 0) {
+ let processedContent = content;
+ if (processedContent?.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, '} {');
+ processedContent = processedContent.replace(/}{/g, '} {');
}
- callback({ content });
+ callback({ content: processedContent });
} catch (e) {
// Send content processing error as normal message with error flag
this.sendErrorMessage(e, 'content_processing_error', callback);
@@ -273,9 +276,9 @@ export default class Chatbot {
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 ...'];
+ // attach to UI debugger
+ (dbgJson as any).function = 'updateStatus';
+ (dbgJson as any).parameters = ['Debugger: Attaching To Agent ...'];
}
callback(dbgJson);
@@ -299,26 +302,26 @@ export default class Chatbot {
await delay(100);
const dbgFunction = `${tool.name} (${args && typeof args === 'object' ? JSON.stringify(args) : args})`;
- let dbgJson = {
+ const dbgJson = {
title: `[${toolHash}] Function Call : ${tool.name}`,
debug: `Debugging ${dbgFunction.substring(0, 50)} ...`,
};
- dbgJson['function'] = 'callParentFunction';
- dbgJson['parameters'] = ['debugLastAction', [], 200];
+ (dbgJson as any).function = 'callParentFunction';
+ (dbgJson as any).parameters = ['debugLastAction', [], 200];
callback(dbgJson);
}
}
if (this.agent.debugSessionEnabled) {
- await delay(3000); //give some time to the UI debugger to attach - FIXME : find a better way to do this
+ await delay(3000); // give some time to the UI debugger to attach - FIXME : find a better way to do this
}
}
- private async afterToolCallHandler({ tool, args }, toolResponse, callback: (response: ChatbotResponse) => void) {
+ private async afterToolCallHandler({ tool }, 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 "} {";
+ // workaround to avoid broken debug message in the frontend
+ // replace all "}{" with "} {";
const _toolResponse = toolResponse.replace(/}\{/g, '}_{');
const chunkSize = 500;
for (let i = 0, len = _toolResponse.length; i < len; i += chunkSize) {
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 0dac394c..ec7dada5 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
@@ -27,8 +27,8 @@ export class FsChatbotContextExporter {
public async *streamConversations({ dateRange, env }: { dateRange?: string; env?: ChatConversationsEnv }): 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;
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 c445dd77..d3c47d26 100644
--- a/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/index.ts
+++ b/packages/runtime/src/modules/embodiment/services/FsChatbotContextStore.class/index.ts
@@ -56,7 +56,7 @@ export class FsChatbotContextStore implements ILLMContextStore {
}
}
- public async getMessage(message_id: string): Promise<any> {
+ public async getMessage(_messageId: string): Promise<any> {
return {};
}
@@ -67,7 +67,7 @@ export class FsChatbotContextStore implements ILLMContextStore {
return [];
}
- const filePath = path.join(folderPath, conversationId + '.json');
+ const filePath = path.join(folderPath, `${conversationId}.json`);
if (!(await fsExists(filePath))) {
return [];
diff --git a/packages/runtime/src/modules/embodiment/utils/general.utils.ts b/packages/runtime/src/modules/embodiment/utils/general.utils.ts
index 39792a63..b7974a80 100644
--- a/packages/runtime/src/modules/embodiment/utils/general.utils.ts
+++ b/packages/runtime/src/modules/embodiment/utils/general.utils.ts
@@ -4,7 +4,7 @@ function uid() {
return (Date.now() + Math.random()).toString(36).replace('.', '').toUpperCase();
}
-const hasKeyTemplateVar = (str: string = ''): boolean => {
+const hasKeyTemplateVar = (str = ''): boolean => {
if (!str || typeof str !== 'string') return false;
return (str?.match(/{{KEY\((.*?)\)}}/g) ?? []).length > 0;
};
@@ -19,11 +19,9 @@ function parseTemplate(str, obj, { escapeString = true, processUnmatched = true,
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');
- }
+ } 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
@@ -33,7 +31,7 @@ function parseTemplate(str, obj, { escapeString = true, processUnmatched = true,
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
+ // 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);