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.

preview file from the runtime (debugger) server

Forhad Hosain1822056b07e4
diff --git a/.vscode/settings.json b/.vscode/settings.json
index c0769343..8a233a89 100644
--- a/.vscode/settings.json
+++ b/.vscode/settings.json
@@ -18,7 +18,7 @@
// ✅ CORRECT CURRENT SETTINGS: Force alias usage
"typescript.suggest.includeAutomaticOptionalChainCompletions": true,
"typescript.updateImportsOnPaste.enabled": true,
- "cSpell.words": ["logto", "smythos"]
+ "cSpell.words": ["logto", "smythfs", "smythos"]
// ✅ Additional helpful settings
}
diff --git a/packages/app/src/backend/routes/dbg/router.ts b/packages/app/src/backend/routes/dbg/router.ts
index 0c9dd9c7..16ce2b11 100644
--- a/packages/app/src/backend/routes/dbg/router.ts
+++ b/packages/app/src/backend/routes/dbg/router.ts
@@ -5,7 +5,6 @@ import { promisify } from 'util';
import config from '../../config';
-import { privateStorage } from '@src/backend/services/storage';
import { createProxyMiddleware, Options } from 'http-proxy-middleware';
import { includeTeamDetails } from '../../middlewares/auth.mw';
const router = express.Router();
@@ -168,10 +167,11 @@ const createSSEProxyOptions: (targetUrl: string) => Options = (targetUrl: string
// Replace the existing SSE proxy route with the new implementation
router.use('/sse', createProxyMiddleware(createSSEProxyOptions(config.env.API_SERVER)));
-// TODO: should be moved to any SRE server
-//! FIX: but this will not work with self-hosted env since SRE is not guranteed to store in S3 and so this
-//! needs to be reloacted to the debugger server
-
+/**
+ * Proxies file read requests to the debugger server
+ * The debugger server has access to SmythFS and can read files from the runtime environment
+ * This approach works for both SaaS and self-hosted environments
+ */
router.get('/file-proxy', includeTeamDetails, async (req, res) => {
const { url } = req.query as { url: string };
@@ -180,7 +180,6 @@ router.get('/file-proxy', includeTeamDetails, async (req, res) => {
return res.status(400).send('Invalid Resource URI');
}
- const resourceId = `teams/${smythURI.team}${smythURI.path}`;
const teamId = req._team?.id;
if (teamId !== smythURI.team) {
@@ -188,67 +187,64 @@ router.get('/file-proxy', includeTeamDetails, async (req, res) => {
}
try {
- // Validate and decode the smythfs URL
+ // Validate the smythfs URL
if (!url.startsWith('smythfs://')) {
return res.status(400).send('Invalid URL format');
}
- // Determine content type based on file extension
- const extension = smythURI.path.split('.').pop()?.toLowerCase();
- const contentType = getContentType(extension);
+ // 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`);
+ debuggerUrl.searchParams.set('url', url);
- // Set appropriate headers for streaming
- res.setHeader('Content-Type', contentType);
- res.setHeader('Accept-Ranges', 'bytes');
-
- // Handle range requests
- const rangeHeader = req.headers.range;
- let s3Range: string | undefined;
- let statusCode = 200;
- let streamOptions: { range?: string } = {};
+ // Forward the range header if present
+ const headers: Record<string, string> = {};
+ if (req.headers.range) {
+ headers.Range = req.headers.range;
+ }
- if (rangeHeader) {
- // Get file size from S3 metadata (assuming we are in SaaS so SRE would store the data in S3)
+ // Make request to debugger server
+ const response = await axios.get(debuggerUrl.toString(), {
+ headers,
+ responseType: 'stream', // Stream the response
+ validateStatus: (status: number) => status < 500, // Treat 4xx as successful so we can forward them to client; only throw on 5xx server errors
+ });
- const meta = await privateStorage.stat(resourceId);
- const fileSize = meta.size;
+ // Forward status code and headers from debugger server
+ res.status(response.status);
- const [startStr, endStr] = rangeHeader.replace(/bytes=/, '').split('-');
- const start = parseInt(startStr, 10);
- const end = endStr ? parseInt(endStr, 10) : fileSize - 1;
+ // Forward relevant headers
+ const headersToForward = ['content-type', 'content-length', 'content-range', 'accept-ranges'];
- if (start >= fileSize || end >= fileSize) {
- res.setHeader('Content-Range', `bytes */${fileSize}`);
- return res.status(416).send('Requested Range Not Satisfiable');
+ for (const header of headersToForward) {
+ const value = response.headers[header];
+ if (value) {
+ res.setHeader(header, value);
}
-
- const chunkSize = end - start + 1;
- streamOptions.range = `bytes=${start}-${end}`;
- statusCode = 206;
-
- res.setHeader('Content-Range', `bytes ${start}-${end}/${fileSize}`);
- res.setHeader('Content-Length', chunkSize);
}
- // Stream via generic adapter
- const fileStream = await privateStorage.getStream(resourceId, streamOptions);
-
- // Handle 'close' event to clean up if client disconnects
- res.on('close', () => (fileStream as any)?.destroy?.());
-
- // Set the status code
- res.status(statusCode);
+ // Handle client disconnect
+ res.on('close', () => {
+ if (response.data && typeof response.data.destroy === 'function') {
+ response.data.destroy();
+ }
+ });
- // Stream the file from S3
- await pipelineAsync(fileStream, res);
+ // Stream the file from debugger server to client
+ await pipelineAsync(response.data, res);
} catch (error: any) {
- // if (error.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
- console.error('Error streaming file /file-proxy:', error?.message);
- if (!res.headersSent) res.status(500).send('Error streaming file');
- // }
+ console.error('Error proxying file from debugger server:', error?.message);
+ if (!res.headersSent) {
+ const status = error.response?.status || 500;
+ const message = error.response?.data || 'Error reading file';
+ res.status(status).send(message);
+ }
}
});
+/**
+ * Parse a smythfs:// URI and extract team and path information
+ */
function URIParser(uri: string) {
const parts = uri.split('://');
if (parts.length !== 2) return undefined;
@@ -266,35 +262,4 @@ function URIParser(uri: string) {
};
}
-/**
- * Get content type based on file extension
- */
-function getContentType(extension?: string): string {
- const contentTypes: Record<string, string> = {
- // Images
- png: 'image/png',
- jpg: 'image/jpeg',
- jpeg: 'image/jpeg',
- gif: 'image/gif',
- webp: 'image/webp',
- // Videos
- mp4: 'video/mp4',
- webm: 'video/webm',
- ogg: 'video/ogg',
- // Audio
- mp3: 'audio/mpeg',
- wav: 'audio/wav',
- // Documents
- pdf: 'application/pdf',
- doc: 'application/msword',
- docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
- // Others
- txt: 'text/plain',
- json: 'application/json',
- csv: 'text/csv',
- };
-
- return contentTypes[extension || ''] || 'application/octet-stream';
-}
-
export default router;
diff --git a/packages/runtime/src/core/router-config.ts b/packages/runtime/src/core/router-config.ts
index 9f97f4fa..20ba3638 100644
--- a/packages/runtime/src/core/router-config.ts
+++ b/packages/runtime/src/core/router-config.ts
@@ -6,6 +6,7 @@ import { processAgentRequest as agentRunnerProcessAgentRequest } from '@agent-ru
import debuggerAgentLoader from '@debugger/middlewares/agentLoader.mw';
import modelsRouter from '@debugger/routes/models/router';
+import smythfsRouter from '@debugger/routes/smythfs/router';
import {
createSseConnection as debuggerCreateSseConnection,
getDebugSession as debuggerGetDebugSession,
@@ -45,6 +46,7 @@ export function configureAgentRouters(app: Express, runtimeConfig?: RuntimeConfi
// Mount common routes that should be available in all server configurations
app.use('/models', modelsRouter);
+ app.use('/smythfs', smythfsRouter);
// Configure based on routing strategy and enabled services
const debuggerEnabled = config.services.debugger.enabled;
diff --git a/packages/runtime/src/modules/debugger/routes/smythfs/router.ts b/packages/runtime/src/modules/debugger/routes/smythfs/router.ts
new file mode 100644
index 00000000..41947095
--- /dev/null
+++ b/packages/runtime/src/modules/debugger/routes/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;