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 smythfs router under user
Forhad Hosain7efb3c56e316
diff --git a/packages/app/src/backend/routes/dbg/router.ts b/packages/app/src/backend/routes/dbg/router.tsindex 16ce2b11..dd8a8c2c 100644--- a/packages/app/src/backend/routes/dbg/router.ts+++ b/packages/app/src/backend/routes/dbg/router.ts@@ -194,7 +194,7 @@ router.get('/file-proxy', includeTeamDetails, async (req, res) => {// Construct the debugger server URL for file streaming// The debugger server will extract agent ID from the URL path- const debuggerUrl = new URL(`${config.env.API_SERVER}/smythfs/stream`);+ const debuggerUrl = new URL(`${config.env.API_SERVER}/user/smythfs/stream`);debuggerUrl.searchParams.set('url', url);// Forward the range header if presentdiff --git a/packages/runtime/src/core/router-config.ts b/packages/runtime/src/core/router-config.tsindex 20ba3638..fe0f6886 100644--- a/packages/runtime/src/core/router-config.ts+++ b/packages/runtime/src/core/router-config.ts@@ -6,18 +6,22 @@ import { processAgentRequest as agentRunnerProcessAgentRequest } from '@agent-ruimport debuggerAgentLoader from '@debugger/middlewares/agentLoader.mw';import modelsRouter from '@debugger/routes/models/router';-import smythfsRouter from '@debugger/routes/smythfs/router';+import userRouter from '@debugger/routes/user/router';import {createSseConnection as debuggerCreateSseConnection,getDebugSession as debuggerGetDebugSession,processAgentRequest as debuggerProcessAgentRequest,} from '@debugger/services/agent-request-handler';+import { Logger } from '@smythos/sre';+import config from './config';import { RuntimeConfig, loadRuntimeConfig, validateRuntimeConfig } from './runtime-config';import { createAgentRunnerRouter, createDebuggerRouter } from './shared-agent-router';import { createConfiguredSmartRouter } from './smart-agent-router';+const console = Logger('[Runtime] Router Config');+/*** Configures and mounts agent routers based on runtime configuration* Designed for future server extraction without code changes@@ -46,7 +50,7 @@ export function configureAgentRouters(app: Express, runtimeConfig?: RuntimeConfi// Mount common routes that should be available in all server configurationsapp.use('/models', modelsRouter);- app.use('/smythfs', smythfsRouter);+ app.use('/user', userRouter);// Configure based on routing strategy and enabled servicesconst debuggerEnabled = config.services.debugger.enabled;diff --git a/packages/runtime/src/modules/debugger/routes/user/router.ts b/packages/runtime/src/modules/debugger/routes/user/router.tsnew file mode 100644index 00000000..831f4938--- /dev/null+++ b/packages/runtime/src/modules/debugger/routes/user/router.ts@@ -0,0 +1,69 @@+import AgentLoader from '@debugger/middlewares/agentLoader.mw';+import { Component, ComponentInstances, ConnectorService, ISchedulerRequest, Logger } from '@smythos/sre';+import express from 'express';+import smythfsRouter from './smythfs.router';++const console = Logger('[Builder] Router: Models');+const router = express.Router();++const middlewares = [AgentLoader];++router.use('/smythfs', smythfsRouter);++const triggerRegisterHandler = async (req, res) => {+ try {+ const { id } = req.params;+ const agentData = req._agent;++ const componentData = agentData.components.find((c: any) => c.id === id);+ const trigger: Component = ComponentInstances[componentData.name];+ if (!trigger) {+ return res.status(404).json({ error: 'Trigger not found' });+ }++ const triggerEndpoint = componentData.data.triggerEndpoint;+ const agentDomain = agentData.domain;+ const isTestDomain = agentData.usingTestDomain;+ let protocol = 'https';+ if (process.env.AGENT_DOMAIN_PORT) {+ if (agentDomain.includes(`.${process.env.AGENT_DOMAIN}`) || agentDomain) {+ protocol = 'http';+ }+ }++ // const triggerUrl = `https://9f5e25c3929d.ngrok-free.app/trigger/${triggerEndpoint}`;+ const triggerUrl = `${req.protocol}://${agentDomain}/trigger/${triggerEndpoint}`;+ // console.log('Registering trigger', triggerUrl, { isTestDomain, agentDomain });+ // await trigger.register(id, componentData.data, { triggerUrl });+ await trigger.register(id, componentData.data, { agentData, triggerUrl });+ return res.status(200).json({ message: 'Trigger registered' });+ } catch (error) {+ // console.error('Error registering trigger', error);+ return res.status(500).json({ error: error.message || 'Internal server error' });+ }+};++router.post('/trigger/:id/register', middlewares, triggerRegisterHandler);+// router.get('/trigger/:id/register', middlewares, triggerRegisterHandler);++router.post(`/schedule/:triggerName`, middlewares, async (req: any, res) => {+ try {+ const agent: any = req._agent;+ const triggerName = req.params.triggerName;+ const schedulerConnector = ConnectorService.getSchedulerConnector();+ if (!schedulerConnector) {+ return res.status(500).json({ error: 'Scheduler connector not found' });+ }++ const schedulerRequester: ISchedulerRequest = schedulerConnector.agent(agent.id);+ const jobId = `job-${agent.id}-${triggerName}`;+ // for testing+ // await schedulerRequester.add(jobId, new Job({ agentId: agent.id, type: 'trigger', triggerName }), Schedule.every('10 seconds'));+ return res.status(200).json({ message: 'Job scheduled successfully' });+ } catch (error) {+ console.error(error);+ return res.status(500).json({ error: 'Failed to schedule job' });+ }+});++export default router;diff --git a/packages/runtime/src/modules/debugger/routes/user/smythfs.router.ts b/packages/runtime/src/modules/debugger/routes/user/smythfs.router.tsnew file mode 100644index 00000000..41947095--- /dev/null+++ b/packages/runtime/src/modules/debugger/routes/user/smythfs.router.ts@@ -0,0 +1,141 @@+import express from 'express';+import { pipeline } from 'stream';+import { promisify } from 'util';++import { AccessCandidate, BinaryInput, Logger, SmythFS } from '@smythos/sre';++const console = Logger('[Builder] Router: File');+const router = express.Router();+const pipelineAsync = promisify(pipeline);++/**+ * Extracts the agent ID from a SmythFS URL+ * Follows the exact pattern from TypeChecker.helper.ts extractSmythFsAgentId+ *+ * @param url - The SmythFS URL (e.g., smythfs://teamId.team/agentId/_temp/filename.ext)+ * @returns The agent ID or null if the URL is invalid+ */+function extractSmythFsAgentId(url: string): string | null {+ if (!url?.startsWith('smythfs://')) return null;++ try {+ // Split by '/' and get the agent ID (third segment)+ const segments = url.split('/');+ if (segments.length < 4) return null;++ return segments[3];+ } catch {+ return null;+ }+}++/**+ * Streams a file from SmythFS to the response+ * Supports range requests for partial content delivery (e.g., video streaming)+ * Follows the BinaryInput pattern from TypeChecker.helper.ts+ *+ * Endpoint: GET /smythfs/stream+ * Query Parameters:+ * - url: The smythfs:// URL to read from (e.g., smythfs://teamId.team/agentId/_temp/file.ext)+ */+router.get('/stream', async (req, res, _next) => {+ try {+ const { url } = req.query as { url: string };++ // Validate required parameters+ if (!url) {+ return res.status(400).send('Missing required parameter: url');+ }++ if (!url.startsWith('smythfs://')) {+ return res.status(400).send('Invalid URL format. Expected smythfs:// URL');+ }++ // Extract agent ID from smythfs:// URL to create an access candidate+ // Following the exact pattern from TypeChecker.helper.ts _createBinaryInput (lines 203, 210, 216)+ const agentId = extractSmythFsAgentId(url);+ if (!agentId) {+ return res.status(400).send('Invalid SmythFS URL: could not extract agent ID');+ }++ // Create access candidate for the agent+ // Following the pattern from TypeChecker.helper.ts line 216+ const candidate = AccessCandidate.agent(agentId);++ // Create BinaryInput following the TypeChecker.helper.ts pattern+ // When value is a smythfs:// URL string, pass it directly as data (line 212)+ // BinaryInput.from(data, fileName, mimetype, candidate) - line 219+ const binaryInput = BinaryInput.from(url, undefined, undefined, candidate);+ await binaryInput.ready();++ // Get metadata from BinaryInput+ const metadata = await SmythFS.Instance.getMetadata(url, candidate);+ if (!metadata) {+ return res.status(404).send('File not found');+ }++ const contentType = metadata.ContentType || 'application/octet-stream';+ const fileSize = metadata.ContentLength || 0;++ // Determine if this is a range request+ const rangeHeader = req.headers.range;++ if (rangeHeader && fileSize > 0) {+ // Handle range request+ const [startStr, endStr] = rangeHeader.replace(/bytes=/, '').split('-');+ const start = parseInt(startStr, 10);+ const end = endStr ? parseInt(endStr, 10) : fileSize - 1;++ if (start >= fileSize || end >= fileSize || start > end) {+ res.setHeader('Content-Range', `bytes */${fileSize}`);+ return res.status(416).send('Requested Range Not Satisfiable');+ }++ const chunkSize = end - start + 1;++ // Set partial content headers+ res.status(206);+ res.setHeader('Content-Range', `bytes ${start}-${end}/${fileSize}`);+ res.setHeader('Content-Length', chunkSize);+ res.setHeader('Content-Type', contentType);+ res.setHeader('Accept-Ranges', 'bytes');++ // Get buffer and send the requested range+ const buffer = await binaryInput.getBuffer();+ const chunk = buffer.subarray(start, end + 1);++ res.send(chunk);+ } else {+ // Handle full file request+ res.setHeader('Content-Type', contentType);+ res.setHeader('Accept-Ranges', 'bytes');++ if (fileSize > 0) {+ res.setHeader('Content-Length', fileSize);+ }++ // Stream the file using BinaryInput's getReadStream method+ const stream = await binaryInput.getReadStream();++ // Handle client disconnect+ res.on('close', () => {+ if (stream && typeof stream.destroy === 'function') {+ stream.destroy();+ }+ });++ await pipelineAsync(stream, res);+ }+ } catch (error: any) {+ console.error('Error reading file:', error?.message || error);++ if (!res.headersSent) {+ if (error.message?.includes('Access Denied')) {+ return res.status(403).send('Access denied');+ }+ return res.status(500).send(error.message || 'Internal Server Error');+ }+ }+});++export default router;