Skip to content

Commit d68adb6

Browse files
Merge pull request #155 from SmythOS/unit-integration-tests-update
Unit integration tests update
2 parents 9024610 + e2437b8 commit d68adb6

File tree

87 files changed

+9394
-376
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

87 files changed

+9394
-376
lines changed

packages/core/package.json

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,10 @@
2727
"build:types": "tsc --emitDeclarationOnly --declaration --outDir dist/types -p tsconfig.dts.json",
2828
"build:jsbundle": "cross-env rollup -c",
2929
"build": "pnpm run build:jsbundle && pnpm run build:types",
30+
"test:unit": "cd ../.. && vitest run packages/core/tests/unit",
31+
"test:unit:watch": "cd ../.. && vitest watch packages/core/tests/unit",
32+
"test:integration": "cd ../.. && vitest run packages/core/tests/integration",
33+
"test:integration:watch": "cd ../.. && vitest watch packages/core/tests/integration",
3034
"gen:docs": "typedoc",
3135
"doc:graphgen": "npx depcruise src --config ./doc/.dep-minimal.json --output-type dot > ./doc/dep-graph.dot && dot -Tpng ./doc/dep-graph.dot -o ./doc/dep-graph.png",
3236
"knip": "knip"

packages/core/src/Components/ECMASandbox.class.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,14 +38,15 @@ export class ECMASandbox extends Component {
3838
}
3939
}
4040

41-
const inputVarsCode = this.generateInputVarCode(codeInputs);
42-
const code = inputVarsCode + '\n' + config.data.code;
41+
//const inputVarsCode = this.generateInputVarCode(codeInputs);
42+
//const code = inputVarsCode + '\n' + config.data.code;
43+
const code = config.data.code;
4344

4445
logger.debug(`Running code: \n${code}\n`);
4546

4647
const ecmaCodeConnector = ConnectorService.getCodeConnector('ECMASandbox');
4748

48-
const executionResponse: CodeExecutionResult = await ecmaCodeConnector.agent(agent.id).execute(config.id, { code });
49+
const executionResponse: CodeExecutionResult = await ecmaCodeConnector.agent(agent.id).execute(config.id, { code, inputs: input });
4950
if (executionResponse.success) {
5051
Output = executionResponse.output;
5152
} else {

packages/core/src/helpers/AWSLambdaCode.helper.ts

Lines changed: 30 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,17 @@ import crypto from 'crypto';
22
import { ConnectorService } from '@sre/Core/ConnectorsService';
33
import { AccessCandidate } from '@sre/Security/AccessControl/AccessCandidate.class';
44
import zl from 'zip-lib';
5-
import { InvokeCommand, Runtime, LambdaClient, UpdateFunctionCodeCommand, CreateFunctionCommand, GetFunctionCommand, GetFunctionCommandOutput, InvokeCommandOutput, UpdateFunctionConfigurationCommand } from '@aws-sdk/client-lambda';
5+
import {
6+
InvokeCommand,
7+
Runtime,
8+
LambdaClient,
9+
UpdateFunctionCodeCommand,
10+
CreateFunctionCommand,
11+
GetFunctionCommand,
12+
GetFunctionCommandOutput,
13+
InvokeCommandOutput,
14+
UpdateFunctionConfigurationCommand,
15+
} from '@aws-sdk/client-lambda';
616
import { GetRoleCommand, CreateRoleCommand, IAMClient, GetRoleCommandOutput, CreateRoleCommandOutput } from '@aws-sdk/client-iam';
717
import fs from 'fs';
818
import { AWSConfig, AWSCredentials, AWSRegionConfig } from '@sre/types/AWS.types';
@@ -19,7 +29,6 @@ export function getLambdaFunctionName(agentId: string, componentId: string) {
1929
return `${agentId}-${componentId}`;
2030
}
2131

22-
2332
export function generateCodeHash(code_body: string, codeInputs: string[], envVariables: string[]) {
2433
const bodyHash = getSanitizeCodeHash(code_body);
2534
const inputsHash = getSanitizeCodeHash(JSON.stringify(codeInputs));
@@ -79,9 +88,7 @@ export async function getDeployedCodeHash(agentId: string, componentId: string)
7988

8089
export async function setDeployedCodeHash(agentId: string, componentId: string, codeHash: string) {
8190
const redisCache = ConnectorService.getCacheConnector();
82-
await redisCache
83-
.user(AccessCandidate.agent(agentId))
84-
.set(`${cachePrefix}_${agentId}-${componentId}`, codeHash, null, null, cacheTTL);
91+
await redisCache.user(AccessCandidate.agent(agentId)).set(`${cachePrefix}_${agentId}-${componentId}`, codeHash, null, null, cacheTTL);
8592
}
8693

8794
function replaceVaultKeysTemplateVars(code: string, envVariables: Record<string, string>) {
@@ -121,7 +128,7 @@ export async function zipCode(directory: string) {
121128
},
122129
function (err) {
123130
reject(err);
124-
},
131+
}
125132
);
126133
});
127134
}
@@ -276,7 +283,6 @@ export function getLambdaRolePolicy() {
276283
});
277284
}
278285

279-
280286
export async function updateDeployedCodeTTL(agentId: string, componentId: string, ttl: number) {
281287
const redisCache = ConnectorService.getCacheConnector();
282288
await redisCache.user(AccessCandidate.agent(agentId)).updateTTL(`${cachePrefix}_${agentId}-${componentId}`, ttl);
@@ -285,7 +291,7 @@ export async function updateDeployedCodeTTL(agentId: string, componentId: string
285291
export async function invokeLambdaFunction(
286292
functionName: string,
287293
inputs: { [key: string]: any },
288-
awsCredentials: AWSCredentials & AWSRegionConfig,
294+
awsCredentials: AWSCredentials & AWSRegionConfig
289295
): Promise<any> {
290296
try {
291297
const client = new LambdaClient({
@@ -384,11 +390,11 @@ export function reportUsage({ cost, agentId, teamId }: { cost: number; agentId:
384390

385391
export function validateAsyncMainFunction(rawCode: string): { isValid: boolean; error?: string; parameters?: string[]; dependencies?: string[] } {
386392
try {
387-
const code = replaceVaultKeysTemplateVars(rawCode, {});
393+
const code = replaceVaultKeysTemplateVars(rawCode.trim(), {});
388394
// Parse the code using acorn
389395
const ast = acorn.parse(code, {
390396
ecmaVersion: 'latest',
391-
sourceType: 'module'
397+
sourceType: 'module',
392398
});
393399

394400
// Extract library imports
@@ -414,22 +420,26 @@ export function validateAsyncMainFunction(rawCode: string): { isValid: boolean;
414420
}
415421

416422
// Handle CallExpression (require() calls)
417-
if (node.type === 'CallExpression' &&
423+
if (
424+
node.type === 'CallExpression' &&
418425
node.callee.type === 'Identifier' &&
419426
node.callee.name === 'require' &&
420427
node.arguments.length > 0 &&
421-
node.arguments[0].type === 'Literal') {
428+
node.arguments[0].type === 'Literal'
429+
) {
422430
const modulePath = node.arguments[0].value;
423431
if (modulePath && !modulePath.startsWith('.') && !modulePath.startsWith('/')) {
424432
libraries.add(extractPackageName(modulePath));
425433
}
426434
}
427435

428436
// Handle dynamic import() calls
429-
if (node.type === 'CallExpression' &&
437+
if (
438+
node.type === 'CallExpression' &&
430439
node.callee.type === 'Import' &&
431440
node.arguments.length > 0 &&
432-
node.arguments[0].type === 'Literal') {
441+
node.arguments[0].type === 'Literal'
442+
) {
433443
const modulePath = node.arguments[0].value;
434444
if (modulePath && !modulePath.startsWith('.') && !modulePath.startsWith('/')) {
435445
libraries.add(extractPackageName(modulePath));
@@ -503,23 +513,23 @@ export function validateAsyncMainFunction(rawCode: string): { isValid: boolean;
503513
return {
504514
isValid: false,
505515
error: 'No main function found at root level',
506-
dependencies
516+
dependencies,
507517
};
508518
}
509519

510520
if (!hasAsyncMain) {
511521
return {
512522
isValid: false,
513523
error: 'Main function exists but is not async',
514-
dependencies
524+
dependencies,
515525
};
516526
}
517527

518528
return { isValid: true, parameters: mainParameters, dependencies };
519529
} catch (error) {
520530
return {
521531
isValid: false,
522-
error: `Failed to parse code: ${error.message}`
532+
error: `Failed to parse code: ${error.message}`,
523533
};
524534
}
525535
}
@@ -549,7 +559,7 @@ export function generateCodeFromLegacyComponent(code_body: string, code_imports:
549559
async function main(${codeInputs.join(', ')}) {
550560
${code_body}
551561
}
552-
`
562+
`;
553563
return code;
554564
}
555565

@@ -565,14 +575,12 @@ export function extractAllKeyNamesFromTemplateVars(input: string): string[] {
565575
return matches;
566576
}
567577

568-
569-
async function fetchVaultSecret(keyName: string, agentTeamId: string): Promise<{ value: string, key: string }> {
578+
async function fetchVaultSecret(keyName: string, agentTeamId: string): Promise<{ value: string; key: string }> {
570579
const vaultSecret = await VaultHelper.getAgentKey(keyName, agentTeamId);
571580
return {
572581
value: vaultSecret,
573582
key: keyName,
574583
};
575-
576584
}
577585

578586
export async function getCurrentEnvironmentVariables(agentTeamId: string, code: string): Promise<Record<string, string>> {
@@ -588,4 +596,4 @@ export async function getCurrentEnvironmentVariables(agentTeamId: string, code:
588596
export function getSortedObjectValues(obj: Record<string, string>): string[] {
589597
const sortedKeys = Object.keys(obj).sort();
590598
return sortedKeys.map((key) => obj[key]);
591-
}
599+
}

packages/core/src/helpers/Conversation.helper.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -132,9 +132,9 @@ export class Conversation extends EventEmitter {
132132
console.warn('Conversation Error: ', error?.message);
133133
});
134134
this._maxContextSize =
135-
_settings.maxContextSize || (this._model as TLLMModel).tokens || (this._model as TLLMModel).keyOptions?.tokens || this._maxContextSize;
135+
_settings?.maxContextSize || (this._model as TLLMModel).tokens || (this._model as TLLMModel).keyOptions?.tokens || this._maxContextSize;
136136
this._maxOutputTokens =
137-
_settings.maxOutputTokens ||
137+
_settings?.maxOutputTokens ||
138138
(this._model as TLLMModel).completionTokens ||
139139
(this._model as TLLMModel).keyOptions?.completionTokens ||
140140
this._maxOutputTokens;
@@ -928,6 +928,7 @@ export class Conversation extends EventEmitter {
928928
//is this a valid agent data?
929929
if (typeof specSource?.behavior === 'string' && specSource?.components && specSource?.connections) {
930930
this.agentData = specSource; //agent loaded from data directly
931+
this._agentId = specSource.id;
931932
return await this.loadSpecFromAgent(specSource);
932933
}
933934

packages/core/src/helpers/ECMASandbox.helper.ts

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,22 @@
11
import 'ses';
22

3-
4-
5-
63
export function runJs(code: string) {
7-
// Call lockdown to secure the environment
8-
lockdown();
4+
// Ensure SES lockdown happens only once per process
5+
// and tolerate environments already locked down elsewhere
6+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
7+
const globalAny: any = globalThis as any;
8+
if (globalAny.__SRE_SES_LOCKED_DOWN__ !== true) {
9+
try {
10+
lockdown();
11+
} catch (err) {
12+
const msg = String(err || '');
13+
if (!(msg.includes('Already locked down') || msg.includes('SES_ALREADY_LOCKED_DOWN'))) {
14+
throw err;
15+
}
16+
} finally {
17+
globalAny.__SRE_SES_LOCKED_DOWN__ = true;
18+
}
19+
}
920
try {
1021
// Endow the compartment with necessary APIs
1122
const compartment = new Compartment({
@@ -27,7 +38,6 @@ export function runJs(code: string) {
2738
console.error(error);
2839
throw error;
2940
}
30-
3141
}
3242

3343
function getParametersString(parameters: string[], inputs: Record<string, any>) {
@@ -49,6 +59,6 @@ export function generateExecutableCode(code: string, parameters: string[], input
4959
const result = await main(${getParametersString(parameters, inputs)});
5060
return result;
5161
})();
52-
`
62+
`;
5363
return executableCode;
5464
}

packages/core/src/subsystems/AgentManager/AgentData.service/connectors/LocalAgentDataConnector.class.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@ import fs from 'fs';
22
import path from 'path';
33
import { AgentDataConnector } from '../AgentDataConnector';
44
import { uid } from '@sre/utils/general.utils';
5+
import { Logger } from '@sre/helpers/Log.helper';
6+
7+
const console = Logger('LocalAgentDataConnector');
58

69
export type LocalAgentDataSettings = { devDir: string; prodDir: string };
710

0 commit comments

Comments
 (0)