SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
add code sandbox to the package
Forhad Hosain0a32a2e5f474
diff --git a/packages/code-sandbox/app.js b/packages/code-sandbox/app.jsnew file mode 100644index 00000000..4a2f6e90--- /dev/null+++ b/packages/code-sandbox/app.js@@ -0,0 +1,50 @@+// function extractNpmImports(code) {+// const importRegex = /import\s+(?:[\w*\s{},]*\s+from\s+)?['"]([^'"]+)['"]/g;+// const requireRegex = /require\(['"]([^'"]+)['"]\)/g;+// const dynamicImportRegex = /import\(['"]([^'"]+)['"]\)/g;++// let libraries = new Set();+// let match;++// // Function to extract the main package name+// function extractPackageName(modulePath) {+// if (modulePath.startsWith("@")) {+// // Handle scoped packages (e.g., @babel/core)+// return modulePath.split("/").slice(0, 2).join("/");+// }+// return modulePath.split("/")[0]; // Extract the first part (main package)+// }++// // Match static ESM imports+// while ((match = importRegex.exec(code)) !== null) {+// libraries.add(extractPackageName(match[1]));+// }++// // Match CommonJS require() calls+// while ((match = requireRegex.exec(code)) !== null) {+// libraries.add(extractPackageName(match[1]));+// }++// // Match dynamic import() calls+// while ((match = dynamicImportRegex.exec(code)) !== null) {+// libraries.add(extractPackageName(match[1]));+// }++// return Array.from(libraries);+// }++// console.log(extractNpmImports(`+// import '@vendor/package-name';+// import { tool } from 'package'+// import * as tool from 'package';+// import express from "express";+// import { readFile } from "fs"+// const axios = require("axios");+// const lodash = require('lodash');+// import "dotenv/config"+// import "@babel/core"+// const dynamic = import("moment/locale/es");+// require('dotenv').config()+// `));+import os from "os";+console.log(os.tmpdir());diff --git a/packages/code-sandbox/ecosystem.config.cjs b/packages/code-sandbox/ecosystem.config.cjsnew file mode 100644index 00000000..4023f752--- /dev/null+++ b/packages/code-sandbox/ecosystem.config.cjs@@ -0,0 +1,17 @@+module.exports = {+ apps: [+ {+ name: "smyth-code-sandbox",+ script: "./index.js",+ autorestart: true,+ exec_mode: "fork",+ watch: false,+ interpreter: "node",+ instances: 1,+ max_memory_restart: "500M",+ env: {+ PORT: "5055",+ },+ },+ ],+};diff --git a/packages/code-sandbox/index.js b/packages/code-sandbox/index.jsnew file mode 100644index 00000000..4de5c986--- /dev/null+++ b/packages/code-sandbox/index.js@@ -0,0 +1,237 @@+import express from "express";+import https from "https";+import vm from "vm";++const app = express();+app.use(express.json({ limit: "10mb" }));++function extractFetchUrls(str) {+ const regex = /\/\/@fetch\((https?:\/\/[^\s]+)\)/g;+ let match;+ const urls = [];++ while ((match = regex.exec(str)) !== null) {+ urls.push(match[1]);+ }++ return urls;+}++function fetchCodeFromCDN(url) {+ return new Promise((resolve, reject) => {+ https+ .get(url, (res) => {+ let data = "";+ res.on("data", (chunk) => (data += chunk));+ res.on("end", () => resolve(data));+ })+ .on("error", reject);+ });+}++function createSafeContext() {+ const context = {+ console: {+ log: (...args) => console.log("[Sandbox]", ...args),+ error: (...args) => console.error("[Sandbox]", ...args),+ warn: (...args) => console.warn("[Sandbox]", ...args),+ info: (...args) => console.info("[Sandbox]", ...args),+ },+ setTimeout: (fn, delay) => setTimeout(fn, Math.min(delay, 5000)), // Max 5s timeout+ setInterval: () => {+ throw new Error("setInterval is not allowed");+ },+ clearTimeout: clearTimeout,+ Math: Math,+ Date: Date,+ JSON: JSON,+ String: String,+ Number: Number,+ Boolean: Boolean,+ Array: Array,+ Object: Object,+ RegExp: RegExp,+ Error: Error,+ ___internal: {+ b64decode: (str) => Buffer.from(str, "base64").toString("utf8"),+ b64encode: (str) => Buffer.from(str, "utf8").toString("base64"),+ },+ _output: undefined,+ global: undefined,+ globalThis: undefined,+ process: undefined,+ require: undefined,+ module: undefined,+ exports: undefined,+ __filename: undefined,+ __dirname: undefined,+ };++ // Make the context reference itself as global+ context.global = context;+ context.globalThis = context;++ return vm.createContext(context);+}++app.post("/compile-js", async (req, res) => {+ let { code } = req.body;++ if (!code) {+ return res.status(400).json({ error: "No code provided" });+ }++ try {+ const context = createSafeContext();++ // Try to compile the script+ const script = new vm.Script(code, {+ filename: "user-code.js",+ timeout: 5000,+ displayErrors: true,+ });++ return res.json({ result: "ok" });+ } catch (error) {+ console.error(error);+ res.status(400).json({ error: "Compile Error - " + error.message });+ }+});++app.post("/run-js", async (req, res) => {+ try {+ console.log("run-js");+ let { code } = req.body;+ if (!code) {+ return res.status(400).json({ error: "No code provided" });+ }++ if (!code.endsWith(";")) code += ";";++ const context = createSafeContext();++ // Handle remote URL fetching+ const remoteUrls = extractFetchUrls(code);+ console.log("remoteUrls", remoteUrls);+ for (const url of remoteUrls) {+ console.log("Fetching", url);+ const remoteCode = await fetchCodeFromCDN(url);+ console.log("importing", url);+ vm.runInContext(remoteCode, context, {+ timeout: 5000,+ displayErrors: true,+ });+ }++ const randomId = Math.random().toString(36).substring(2, 15);+ const resId = `res${randomId}`;++ // Prepare the script code+ const scriptCode = `+ var ${resId};+ ${code};+ ${resId} = JSON.stringify(_output);+ ${resId};+ `;++ console.log("----------");+ console.log(scriptCode);+ console.log("----------");++ try {+ const script = new vm.Script(scriptCode, {+ filename: "user-code.js",+ timeout: 5000,+ displayErrors: true,+ });++ const rawResult = script.runInContext(context, {+ timeout: 5000,+ displayErrors: true,+ });++ const Output = JSON.parse(rawResult);+ return res.json({ Output });+ } catch (compileError) {+ console.error("Compile/Run Error:", compileError);+ return res+ .status(400)+ .json({ error: "Execution Error - " + compileError.message });+ }+ } catch (error) {+ console.error(error);+ res.status(500).json({ error: error.message });+ }+});++app.post("/run-js/async", async (req, res) => {+ try {+ let { code } = req.body;+ if (!code) {+ return res.status(400).json({ error: "No code provided" });+ }++ if (!code.endsWith(";")) code += ";";++ const context = createSafeContext();++ // Handle remote URL fetching+ const remoteUrls = extractFetchUrls(code);+ for (const url of remoteUrls) {+ const remoteCode = await fetchCodeFromCDN(url);+ vm.runInContext(remoteCode, context, {+ timeout: 5000,+ displayErrors: true,+ });+ }++ const randomId = Math.random().toString(36).substring(2, 15);+ const resId = `res${randomId}`;++ const scriptCode = `+ (async () => {+ let ${resId};+ ${code}+ if(typeof _output === 'object') {+ ${resId} = JSON.stringify(_output);+ } else {+ ${resId} = _output;+ }+ return ${resId};+ })()+ `;++ // For async, we'll use a Promise-based approach+ const asyncScript = new vm.Script(+ `+ const asyncFunc = ${scriptCode};+ asyncFunc;+ `,+ {+ filename: "user-code-async.js",+ timeout: 5000,+ displayErrors: true,+ }+ );++ const asyncFunction = asyncScript.runInContext(context, {+ timeout: 5000,+ displayErrors: true,+ });++ // Note: This is a simplified async handling - full Promise support would require more work+ const rawResult = await Promise.resolve(asyncFunction);+ const Output = JSON.parse(rawResult);++ return res.json({ Output });+ } catch (error) {+ console.error(error);+ res.status(500).json({ error: error.message });+ }+});++const PORT = 5055;+app.listen(PORT, () => {+ console.log(`Code Sandbox Server running on http://localhost:${PORT}`);+ console.log("Using Node.js built-in VM for sandboxing");+});diff --git a/packages/code-sandbox/package.json b/packages/code-sandbox/package.jsonnew file mode 100644index 00000000..5444543b--- /dev/null+++ b/packages/code-sandbox/package.json@@ -0,0 +1,20 @@+{+ "name": "smyth-code-sandbox",+ "version": "1.0.0",+ "description": "",+ "main": "index.js",+ "type": "module",+ "engines": {+ "node": ">=18",+ "npm": ">=8.0.0"+ },+ "scripts": {+ "start": "node index.js",+ "test": "echo \"Error: no test specified\" && exit 1"+ },+ "author": "",+ "license": "ISC",+ "dependencies": {+ "express": "^4.18.2"+ }+}diff --git a/packages/runtime/src/core/component/Code.class.ts b/packages/runtime/src/core/component/Code.class.tsindex 7a791cac..4e1cae6d 100644--- a/packages/runtime/src/core/component/Code.class.ts+++ b/packages/runtime/src/core/component/Code.class.ts@@ -20,7 +20,7 @@ export class Code extends Component {try {let Output: any = {};let _error = undefined;- const url = process.env.CODE_SANDBOX_URL + "/run-js";+ const url = (process.env.CODE_SANDBOX_URL || "http://localhost:5055") + "/run-js";let codeInputs = {};for (let fieldName in input) {diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.tsindex d6d986d5..b8dba0aa 100644--- a/packages/runtime/src/index.ts+++ b/packages/runtime/src/index.ts@@ -32,6 +32,9 @@ import {// Embodiment importsimport { routes as embodimentRoutes } from "@embodiment/routes";+// Code sandbox service+import { CodeSandboxService } from "./services/code-sandbox.service";+const app = express();const port = parseInt(process.env.PORT || "5000");@@ -195,12 +198,36 @@ app.use(notFoundHandler);app.use(errorHandler);let server: Server | null = null;+const codeSandboxService = CodeSandboxService.getInstance();+(async () => {try {+ console.info("🚀 Starting SmythOS Runtime Services...");+ console.info("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");++ // Start the code sandbox service+ console.info("📦 Starting Code Sandbox Service...");+ await codeSandboxService.start();+ console.info(`✅ Code Sandbox Service running on http://localhost:5055`);++ // Start the main servers (runtime + management)+ console.info("⚡ Starting Main Runtime Services...");server = startServers();- console.info(`Server started on port ${port}`);++ // Log all running services+ console.info("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");+ console.info("🎯 All Services Running:");+ console.info(+ ` • Management Server: http://localhost:${+ process.env.ADMIN_PORT || "8080"+ }`+ );+ console.info(` • Runtime Server: http://localhost:${port}`);+ console.info(` • Code Sandbox: http://localhost:5055`);+ console.info("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");+ console.info("✨ SmythOS Runtime is ready!");} catch (error) {- console.error(error);+ console.error("❌ Failed to start services:", error);}})();@@ -209,4 +236,30 @@ process.on("uncaughtException", (err) => {console.error(err.stack);});+// Graceful shutdown+const gracefulShutdown = async (signal: string) => {+ console.info(`Received ${signal}, shutting down gracefully`);++ try {+ // Stop code sandbox service+ await codeSandboxService.stop();++ // Close HTTP server if it exists+ if (server) {+ server.close(() => {+ console.info("HTTP server closed");+ process.exit(0);+ });+ } else {+ process.exit(0);+ }+ } catch (error) {+ console.error("Error during shutdown:", error);+ process.exit(1);+ }+};++process.on("SIGTERM", () => gracefulShutdown("SIGTERM"));+process.on("SIGINT", () => gracefulShutdown("SIGINT"));+export { app };diff --git a/packages/runtime/src/services/code-sandbox.service.ts b/packages/runtime/src/services/code-sandbox.service.tsnew file mode 100644index 00000000..41651477--- /dev/null+++ b/packages/runtime/src/services/code-sandbox.service.ts@@ -0,0 +1,101 @@+import { Logger } from "@smythos/sre";+import { ChildProcess, spawn } from "child_process";+import path from "path";++const console = Logger("code-sandbox-service");++export class CodeSandboxService {+ private static instance: CodeSandboxService;+ private sandboxProcess: ChildProcess | null = null;+ private readonly sandboxPort = 5055;++ static getInstance(): CodeSandboxService {+ if (!CodeSandboxService.instance) {+ CodeSandboxService.instance = new CodeSandboxService();+ }+ return CodeSandboxService.instance;+ }++ async start(): Promise<void> {+ try {+ const scriptPath = path.join(+ process.cwd(),+ "..",+ "code-sandbox",+ "index.js"+ );++ console.info(`Starting code sandbox service on port ${this.sandboxPort}`);++ this.sandboxProcess = spawn("node", [scriptPath], {+ stdio: ["inherit", "pipe", "pipe"],+ env: { ...process.env },+ });++ this.sandboxProcess.stdout?.on("data", (data) => {+ console.info(`[Code Sandbox] ${data.toString().trim()}`);+ });++ this.sandboxProcess.stderr?.on("data", (data) => {+ console.error(`[Code Sandbox Error] ${data.toString().trim()}`);+ });++ this.sandboxProcess.on("exit", (code, signal) => {+ console.warn(+ `Code sandbox process exited with code ${code} and signal ${signal}`+ );+ this.sandboxProcess = null;+ });++ this.sandboxProcess.on("error", (error) => {+ console.error("Failed to start code sandbox process:", error);+ });++ // Give it a moment to start+ await new Promise((resolve) => setTimeout(resolve, 2000));++ console.info("Code sandbox service started successfully");+ } catch (error) {+ console.error("Failed to start code sandbox service:", error);+ throw error;+ }+ }++ async stop(): Promise<void> {+ if (this.sandboxProcess) {+ console.info("Stopping code sandbox service");+ this.sandboxProcess.kill("SIGTERM");++ // Wait for graceful shutdown, then force kill if needed+ await new Promise((resolve) => {+ if (!this.sandboxProcess) {+ resolve(undefined);+ return;+ }++ const timeout = setTimeout(() => {+ if (this.sandboxProcess) {+ console.warn("Force killing code sandbox process");+ this.sandboxProcess.kill("SIGKILL");+ }+ resolve(undefined);+ }, 5000);++ this.sandboxProcess.on("exit", () => {+ clearTimeout(timeout);+ resolve(undefined);+ });+ });++ this.sandboxProcess = null;+ }+ }++ isRunning(): boolean {+ return this.sandboxProcess !== null && !this.sandboxProcess.killed;+ }++ getSandboxUrl(): string {+ return `http://localhost:${this.sandboxPort}`;+ }+}