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.

remove code component

Forhad Hosain9d374e97b55f
diff --git a/packages/code-sandbox/app.js b/packages/code-sandbox/app.js
deleted file mode 100644
index 4a2f6e90..00000000
--- a/packages/code-sandbox/app.js
+++ /dev/null
@@ -1,50 +0,0 @@
-// 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.cjs
deleted file mode 100644
index 4023f752..00000000
--- a/packages/code-sandbox/ecosystem.config.cjs
+++ /dev/null
@@ -1,17 +0,0 @@
-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.js
deleted file mode 100644
index ea07db0e..00000000
--- a/packages/code-sandbox/index.js
+++ /dev/null
@@ -1,195 +0,0 @@
-import express from "express";
-import https from "https";
-import "ses";
-
-// Call lockdown once at startup to secure the environment
-lockdown();
-
-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 createSafeCompartment() {
- // Create a secure compartment with hardened globals
- const compartment = new Compartment({
- globals: {
- console: harden({
- 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: harden((fn, delay) => setTimeout(fn, Math.min(delay, 5000))),
- clearTimeout: harden(clearTimeout),
- Math: harden(Math),
- Date: harden(Date),
- JSON: harden(JSON),
- String: harden(String),
- Number: harden(Number),
- Boolean: harden(Boolean),
- Array: harden(Array),
- Object: harden(Object),
- RegExp: harden(RegExp),
- Error: harden(Error),
- Promise: harden(Promise),
- ___internal: harden({
- b64decode: (str) => Buffer.from(str, "base64").toString("utf8"),
- b64encode: (str) => Buffer.from(str, "utf8").toString("base64"),
- }),
- _output: undefined,
- },
- __options__: true, // temporary migration affordance
- });
-
- return compartment;
-}
-
-app.post("/compile-js", async (req, res) => {
- let { code } = req.body;
-
- if (!code) {
- return res.status(400).json({ error: "No code provided" });
- }
-
- try {
- const compartment = createSafeCompartment();
-
- // Try to compile the code by evaluating it in the compartment
- compartment.evaluate(code);
-
- 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 compartment = createSafeCompartment();
-
- // 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);
- compartment.evaluate(remoteCode);
- }
-
- 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 rawResult = compartment.evaluate(scriptCode);
- 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 compartment = createSafeCompartment();
-
- // Handle remote URL fetching
- const remoteUrls = extractFetchUrls(code);
- for (const url of remoteUrls) {
- const remoteCode = await fetchCodeFromCDN(url);
- compartment.evaluate(remoteCode);
- }
-
- 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};
- })()
- `;
-
- // Evaluate the async code in the compartment
- const asyncFunction = compartment.evaluate(scriptCode);
-
- // 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 SES (Secure EcmaScript) for secure sandboxing");
-});
diff --git a/packages/code-sandbox/package.json b/packages/code-sandbox/package.json
deleted file mode 100644
index b42cc6cb..00000000
--- a/packages/code-sandbox/package.json
+++ /dev/null
@@ -1,21 +0,0 @@
-{
- "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",
- "ses": "^1.14.0"
- }
-}
diff --git a/packages/runtime/.env.example b/packages/runtime/.env.example
index ec21fbba..87544012 100644
--- a/packages/runtime/.env.example
+++ b/packages/runtime/.env.example
@@ -21,6 +21,3 @@ DEFAULT_AGENT_DOMAIN="localagent.stage.smyth.ai"
PROD_AGENT_DOMAIN="agentid.smythos.com"
AGENT_DOMAIN_PORT="5053"
BUILD="dev"
-
-# Optional
-CODE_SANDBOX_URL='http://localhost:5055' # url to code sandbox used for code component
diff --git a/packages/runtime/src/core/component/Code.class.ts b/packages/runtime/src/core/component/Code.class.ts
deleted file mode 100644
index b9c5e625..00000000
--- a/packages/runtime/src/core/component/Code.class.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { Agent, Component, TemplateStringHelper } from "@smythos/sre";
-import axios from "axios";
-import Joi from "joi";
-
-export class Code extends Component {
- protected configSchema = Joi.object({
- code_vars: Joi.string().max(1000).allow("").label("Variables"),
- code_body: Joi.string().max(500000).allow("").label("Code"),
- _templateSettings: Joi.object().allow(null).label("Template Settings"),
- _templateVars: Joi.object().allow(null).label("Template Variables"),
- });
- constructor() {
- super();
- }
- init() {}
- async process(input, config, agent: Agent) {
- await super.process(input, config, agent);
-
- const logger = this.createComponentLogger(agent, config);
- try {
- let Output: any = {};
- let _error = undefined;
- const url = config.env.CODE_SANDBOX_URL + "/run-js";
-
- let codeInputs = {};
- for (let fieldName in input) {
- const _type = typeof input[fieldName];
- switch (_type) {
- case "string":
- //escape string
- //codeInputs[fieldName] = `\`${input[fieldName]}\``;
-
- //encode string
- const b64encoded = Buffer.from(input[fieldName]).toString("base64");
- codeInputs[fieldName] = `___internal.b64decode('${b64encoded}')`;
-
- break;
- case "number":
- case "boolean":
- codeInputs[fieldName] = input[fieldName];
- break;
- default:
- codeInputs[fieldName] = input[fieldName];
- break;
- }
- }
- //FIXME : don't trust code_vars from user input ==> generate it
-
- // let code_vars = parseTemplate(config.data.code_vars || '', codeInputs, { escapeString: false, processUnmatched: false });
- let code_vars = TemplateStringHelper.create(config.data.code_vars || "")
- .parse(codeInputs)
- .clean(undefined, "undefined").result;
-
- //TODO: the current template parser doesn't support the processUnmatched or unmached options !!!!
- // code_vars = parseTemplate(code_vars || '', codeInputs, { escapeString: false, unmached: 'undefined' });
- let code_body = config.data.code_body;
- if (config.data._templateVars) {
- // code_body = parseTemplate(code_body, config.data._templateVars);
- code_body = TemplateStringHelper.create(code_body).parse(
- config.data._templateVars
- ).result;
- }
- const code = code_vars + "\n" + code_body;
-
- logger.debug(` Running code \n${code}\n`);
-
- const result: any = await axios
- .post(url, { code })
- .catch((error) => ({ error }));
-
- if (result.error) {
- _error =
- result.error?.response?.data ||
- result.error?.message ||
- result.error.toString() ||
- "Unknown error";
- logger.error(
- ` Error running code \n${JSON.stringify(result.error, null, 2)}\n`
- );
- Output = undefined; //prevents running next component if the code execution failed
- } else {
- logger.debug(
- ` Code result \n${JSON.stringify(result.data, null, 2)}\n`
- );
- Output = result.data?.Output;
- }
-
- return { Output, _error, _debug: logger.output };
- } catch (err: any) {
- const _error = err?.response?.data || err?.message || err.toString();
- logger.error(` Error running code \n${_error}\n`);
- return { Output: undefined, _error, _debug: logger.output };
- }
- }
-}
diff --git a/packages/runtime/src/core/component/componentRegistry.ts b/packages/runtime/src/core/component/componentRegistry.ts
deleted file mode 100644
index c33afcbd..00000000
--- a/packages/runtime/src/core/component/componentRegistry.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import {
- AccessCandidate,
- ComponentConnector,
- ConnectorService,
-} from "@smythos/sre";
-
-import { Code } from "./Code.class";
-
-const COMPONENTS = [["Code", Code]] as const;
-
-/**
- * Register all components
- */
-export function registerComponents(): void {
- const componentConnector =
- ConnectorService.getComponentConnector() as ComponentConnector;
- const requester = componentConnector.requester(
- AccessCandidate.user("system")
- );
-
- COMPONENTS.forEach(([name, componentClass]) => {
- requester.register(name, new componentClass());
- });
-}
diff --git a/packages/runtime/src/core/config.ts b/packages/runtime/src/core/config.ts
index 11948e81..96a579b3 100644
--- a/packages/runtime/src/core/config.ts
+++ b/packages/runtime/src/core/config.ts
@@ -33,8 +33,6 @@ const config = {
UI_SERVER: process.env.UI_SERVER || "http://localhost:4000",
SESSION_SECRET: process.env.SESSION_SECRET,
- CODE_SANDBOX_URL: process.env.CODE_SANDBOX_URL || "http://localhost:5055",
-
DATA_PATH: process.env.DATA_PATH || path.resolve(__dirname, "../../data"),
SMYTHOS_SERVER_TYPE: process.env.SMYTHOS_SERVER_TYPE || "combined",
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index c565a529..eda6ca3e 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -18,7 +18,6 @@ import RateLimiter from "@core/middlewares/rateLimiter.mw";
import { uploadHandler } from "@core/middlewares/uploadHandler.mw";
import { requestContext } from "@core/services/request-context";
-import { registerComponents } from "@core/component/componentRegistry";
import { registerConnectors } from "@core/connectors/connectorRegistry";
// Routes are handled by configureAgentRouters
@@ -32,19 +31,12 @@ import {
// Embodiment imports
import { routes as embodimentRoutes } from "@embodiment/routes";
-// Code sandbox service
-import { CodeSandboxService } from "./services/code-sandbox.service";
-
const app = express();
const port = config.env.PORT;
// Register all connectors
registerConnectors();
-SystemEvents.on("SRE:Initialized", (SRE) => {
- registerComponents();
-});
-
const sre = SmythRuntime.Instance.init({
Cache: {
Connector: "RAM",
@@ -94,10 +86,6 @@ const sre = SmythRuntime.Instance.init({
Connector: "ConsoleLog",
Settings: {},
},
- Code: {
- Connector: "ECMASandbox",
- Settings: {},
- },
});
const __filename = url.fileURLToPath(import.meta.url);
@@ -200,18 +188,12 @@ 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();
@@ -225,7 +207,7 @@ const codeSandboxService = CodeSandboxService.getInstance();
}`
);
console.info(` • Runtime Server: http://localhost:${port}`);
- console.info(` • Code Sandbox: http://localhost:5055`);
+
console.info("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
console.info("✨ SmythOS Runtime is ready!");
} catch (error) {
@@ -243,9 +225,6 @@ 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(() => {
diff --git a/packages/runtime/src/services/code-sandbox.service.ts b/packages/runtime/src/services/code-sandbox.service.ts
deleted file mode 100644
index 9d26a950..00000000
--- a/packages/runtime/src/services/code-sandbox.service.ts
+++ /dev/null
@@ -1,102 +0,0 @@
-import { ChildProcess, spawn } from "child_process";
-import path from "path";
-
-import { Logger } from "@smythos/sre";
-
-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}`;
- }
-}