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.

resolve import for agent-runner

Forhad Hosain14e4ac48788d
diff --git a/packages/runtime/README.md b/packages/runtime/README.md
index ed6d2438..98f0a42c 100644
--- a/packages/runtime/README.md
+++ b/packages/runtime/README.md
@@ -6,6 +6,33 @@ A Runtime Server that combines the functionality of three separate SmythOS Runti
- **sre-builder-debugger** (Debugger)
- **sre-embodiment-server** (Embodiment)
+## 📚 Table of Contents
+
+- [🚀 Quick Start - Smart Routing](#-quick-start---smart-routing)
+- [🚀 Smart Routing System](#-smart-routing-system) ⭐ **New!**
+- [Server Modes](#server-modes)
+- [Installation & Usage](#installation--usage)
+- [Configuration](#configuration)
+- [Health Check](#health-check)
+
+## 🚀 Quick Start - Smart Routing
+
+```bash
+# Default (Agent Runner)
+curl http://localhost:5000/api/test
+
+# Force Agent Runner
+curl -H "X-FORCE-AGENT-RUNNER: true" http://localhost:5000/api/test
+
+# Force Debugger
+curl -H "X-FORCE-DEBUGGER: true" http://localhost:5000/api/test
+
+# Debug Session
+curl -H "X-DEBUG-RUN: true" http://localhost:5000/api/test
+```
+
+> 📖 **[See full Smart Routing documentation below](#-smart-routing-system)**
+
## Server Modes
The server can run in different modes based on the `SERVER_MODE` environment variable:
@@ -154,3 +181,251 @@ This Runtime Server replaces the need for running three separate servers:
- Swagger documentation
- Form preview functionality
- Agent chat interface
+
+## 🚀 Smart Routing System
+
+The Runtime Server features an intelligent routing system that automatically directs requests to the appropriate service (Agent Runner or Debugger) based on HTTP headers. This provides **predictable, header-based routing** that works consistently across all environments.
+
+### 🎯 Quick Start
+
+**Default Behavior (No Headers)**
+
+```bash
+curl http://localhost:5000/api/test
+# → Routes to Agent Runner (production-safe default)
+```
+
+**Force Agent Runner**
+
+```bash
+curl -H "X-FORCE-AGENT-RUNNER: true" http://localhost:5000/api/test
+# → Always routes to Agent Runner
+```
+
+**Force Debugger**
+
+```bash
+curl -H "X-FORCE-DEBUGGER: true" http://localhost:5000/api/test
+# → Always routes to Debugger
+```
+
+**Debug Session**
+
+```bash
+curl -H "X-DEBUG-RUN: true" http://localhost:5000/api/test
+# → Routes to Debugger for debugging
+```
+
+### 📋 Routing Priority (Highest to Lowest)
+
+| Priority | Header | Routes To | Use Case |
+| -------- | --------------------------- | ------------ | ------------------------- |
+| 1 | `X-FORCE-AGENT-RUNNER` | Agent Runner | Force production behavior |
+| 2 | `X-DEBUG-*`, `X-MONITOR-ID` | Debugger | Debug sessions |
+| 3 | `X-FORCE-DEBUGGER` | Debugger | Force debug behavior |
+| 4 | Deployed versions | Agent Runner | Production safety |
+| 5 | `X-ROUTING-MODE` | As specified | Explicit routing |
+| 6 | No headers | Agent Runner | Safe default |
+
+### 🔧 Available Headers
+
+#### Force Routing Headers
+
+```bash
+# Force Agent Runner (highest priority)
+X-FORCE-AGENT-RUNNER: true
+
+# Force Debugger
+X-FORCE-DEBUGGER: true
+```
+
+#### Debug Session Headers
+
+```bash
+# Any of these will route to Debugger
+X-DEBUG-RUN: true
+X-DEBUG-STOP: true
+X-DEBUG-READ: true
+X-DEBUG-INJ: true
+X-DEBUG-SKIP: true
+X-MONITOR-ID: your-monitor-id
+```
+
+#### Explicit Mode Headers
+
+```bash
+# Explicit routing mode
+X-ROUTING-MODE: debugger # Routes to Debugger
+X-ROUTING-MODE: agent-runner # Routes to Agent Runner
+```
+
+### 🧪 Testing Different Environments
+
+#### Test Agent Runner from Localhost
+
+```bash
+# Without header (old behavior might route to debugger)
+curl http://localhost:5000/api/test
+
+# With header (guaranteed agent runner)
+curl -H "X-FORCE-AGENT-RUNNER: true" http://localhost:5000/api/test
+```
+
+#### Test Debugger from Production
+
+```bash
+# Force debugger even on production domains
+curl -H "X-FORCE-DEBUGGER: true" https://your-agent.com/api/test
+```
+
+#### Debug Sessions
+
+```bash
+# Start a debug session
+curl -H "X-DEBUG-RUN: true" http://localhost:5000/api/test
+
+# Monitor agent execution
+curl -H "X-MONITOR-ID: session-123" http://localhost:5000/api/test
+```
+
+### 🛠️ For Developers
+
+#### Example Scripts
+
+We provide ready-to-use test scripts:
+
+```bash
+# Test routing logic programmatically
+node examples/test-smart-routing.js
+
+# Test routing with actual HTTP requests (server must be running)
+./examples/test-routing-http.sh
+```
+
+#### Testing Routing Logic
+
+```typescript
+import { testRoutingDecision, RoutingHeaders } from "./core/smart-agent-router";
+
+const agent = { agentVersion: "development" };
+
+// Test different scenarios
+const scenarios = [
+ { headers: RoutingHeaders.FORCE_AGENT_RUNNER, expected: "agent-runner" },
+ { headers: RoutingHeaders.DEBUG_RUN, expected: "debugger" },
+ { headers: RoutingHeaders.NONE, expected: "agent-runner" },
+];
+
+scenarios.forEach(({ headers, expected }) => {
+ const result = testRoutingDecision(agent, headers);
+ console.log(`Headers: ${JSON.stringify(headers)}`);
+ console.log(`Routes to: ${result.useDebugger ? "debugger" : "agent-runner"}`);
+ console.log(`Reason: ${result.reason}\n`);
+});
+```
+
+#### Available Test Headers
+
+```typescript
+import { RoutingHeaders } from "./core/smart-agent-router";
+
+// Pre-defined header combinations
+RoutingHeaders.FORCE_AGENT_RUNNER; // { "X-FORCE-AGENT-RUNNER": "true" }
+RoutingHeaders.FORCE_DEBUGGER; // { "X-FORCE-DEBUGGER": "true" }
+RoutingHeaders.DEBUG_RUN; // { "X-DEBUG-RUN": "true" }
+RoutingHeaders.DEBUG_STOP; // { "X-DEBUG-STOP": "true" }
+RoutingHeaders.MODE_DEBUGGER; // { "X-ROUTING-MODE": "debugger" }
+RoutingHeaders.MODE_AGENT_RUNNER; // { "X-ROUTING-MODE": "agent-runner" }
+RoutingHeaders.NONE; // {} (no headers)
+```
+
+### 🔍 Troubleshooting
+
+#### Request Not Routing as Expected?
+
+1. **Check your headers**: Use browser dev tools or `curl -v` to verify headers
+2. **Check the logs**: The server logs routing decisions with reasons
+3. **Test with explicit headers**: Use `X-FORCE-*` headers to override behavior
+
+#### Common Issues
+
+**Issue**: "Agent always routes to debugger from localhost"
+
+```bash
+# Solution: Use explicit header
+curl -H "X-FORCE-AGENT-RUNNER: true" http://localhost:5000/api/test
+```
+
+**Issue**: "Can't debug from production domain"
+
+```bash
+# Solution: Use debug header
+curl -H "X-FORCE-DEBUGGER: true" https://production.com/api/test
+```
+
+**Issue**: "Routing is inconsistent"
+
+```bash
+# Solution: Use explicit routing mode
+curl -H "X-ROUTING-MODE: agent-runner" http://your-domain.com/api/test
+```
+
+### 📊 Monitoring
+
+The server logs all routing decisions:
+
+```
+Routing decision: AGENT-RUNNER - X-FORCE-AGENT-RUNNER header present
+Routing decision: DEBUGGER - Debug headers present
+Routing decision: AGENT-RUNNER - Default production-safe routing
+```
+
+### 🎯 Best Practices
+
+1. **Production**: No headers = safe default (Agent Runner)
+2. **Development**: Use explicit headers for predictable behavior
+3. **Testing**: Use `X-FORCE-*` headers to test specific services
+4. **Debugging**: Use `X-DEBUG-*` headers for debug sessions
+5. **CI/CD**: Use `X-ROUTING-MODE` for explicit test scenarios
+
+### 🔄 Migration from Domain-Based Routing
+
+If you were relying on domain-based routing:
+
+**Old Way** (unreliable):
+
+```bash
+# Localhost = debugger, production = agent-runner (unpredictable)
+curl http://localhost:5000/api/test
+```
+
+**New Way** (explicit):
+
+```bash
+# Explicit header-based routing (predictable)
+curl -H "X-FORCE-AGENT-RUNNER: true" http://localhost:5000/api/test
+curl -H "X-FORCE-DEBUGGER: true" http://production.com/api/test
+```
+
+---
+
+## 📁 Examples Directory
+
+The `examples/` directory contains helpful scripts for testing and understanding the Smart Routing system:
+
+- **`test-smart-routing.js`** - Programmatic testing of routing logic
+- **`test-routing-http.sh`** - HTTP request testing with curl
+- Run these scripts to validate your routing configuration
+
+## 🤝 Contributing
+
+When contributing to the Smart Routing system:
+
+1. **Test all scenarios** using the provided example scripts
+2. **Update documentation** if adding new headers or routing logic
+3. **Maintain backward compatibility** with existing debug headers
+4. **Follow the priority system** when adding new routing rules
+
+## 📄 License
+
+This project is part of the SmythOS Runtime system.
diff --git a/packages/runtime/package.json b/packages/runtime/package.json
index ae2be9c9..4ab3fab8 100644
--- a/packages/runtime/package.json
+++ b/packages/runtime/package.json
@@ -22,6 +22,7 @@
"@types/express-http-proxy": "^1.6.6",
"@types/node": "^22.9.0",
"@types/swagger-ui-express": "^4.1.7",
+ "@types/uuid": "^9.0.8",
"cross-env": "^7.0.3",
"pkg": "^5.8.1",
"rollup": "^2.79.2",
@@ -31,6 +32,8 @@
"rollup-plugin-terser": "^7.0.2",
"rollup-plugin-typescript-paths": "^1.5.0",
"rollup-plugin-typescript2": "^0.36.0",
+ "ts-node": "^10.9.0",
+ "typescript": "^5.0.0",
"vite-tsconfig-paths": "^5.1.2",
"vitest": "^2.1.4"
},
@@ -55,9 +58,11 @@
"openai": "^4.72.0",
"openapi-to-postmanv2": "^4.24.0",
"pkce-challenge": "^5.0.0",
+ "qs": "^6.14.0",
"rate-limiter-flexible": "^5.0.4",
"swagger-ui-dist": "^5.18.2",
"swagger-ui-express": "^5.0.0",
+ "uuid": "^9.0.1",
"winston": "^3.17.0"
}
}
diff --git a/packages/runtime/src/core/router-config.ts b/packages/runtime/src/core/router-config.ts
new file mode 100644
index 00000000..096406f0
--- /dev/null
+++ b/packages/runtime/src/core/router-config.ts
@@ -0,0 +1,247 @@
+import { Express } from "express";
+import {
+ RuntimeConfig,
+ loadRuntimeConfig,
+ validateRuntimeConfig,
+} from "./runtime-config";
+import {
+ createAgentRunnerRouter,
+ createDebuggerRouter,
+} from "./shared-agent-router";
+import { createConfiguredSmartRouter } from "./smart-agent-router";
+
+// Debugger imports
+import debuggerAgentLoader from "@debugger/middlewares/agentLoader.mw";
+import {
+ createSseConnection as debuggerCreateSseConnection,
+ getDebugSession as debuggerGetDebugSession,
+ processAgentRequest as debuggerProcessAgentRequest,
+} from "@debugger/services/agent-request-handler";
+
+// Agent-runner imports
+import agentRunnerAgentLoader from "@agent-runner/middlewares/agentLoader.mw";
+import { processAgentRequest as agentRunnerProcessAgentRequest } from "@agent-runner/services/agent-request-handler";
+import { uploadHandler } from "@core/middlewares/uploadHandler.mw";
+
+/**
+ * Configures and mounts agent routers based on runtime configuration
+ * Designed for future server extraction without code changes
+ *
+ * The extraction script will set SMYTHOS_SERVER_TYPE environment variable:
+ * - 'combined': All services in one server (default)
+ * - 'debugger': Only debugger service
+ * - 'agent-runner': Only agent-runner service
+ * - 'embodiment': Only embodiment service
+ */
+export function configureAgentRouters(
+ app: Express,
+ runtimeConfig?: RuntimeConfig
+) {
+ const config = runtimeConfig || loadRuntimeConfig();
+
+ // Validate configuration
+ const validation = validateRuntimeConfig(config);
+ if (!validation.valid) {
+ throw new Error(
+ `Invalid runtime configuration: ${validation.errors.join(", ")}`
+ );
+ }
+
+ console.log(`Configuring ${config.serverType} server with services:`, {
+ debugger: config.services.debugger.enabled,
+ agentRunner: config.services.agentRunner.enabled,
+ embodiment: config.services.embodiment.enabled,
+ routing: config.routing.strategy,
+ });
+
+ // Configure based on routing strategy and enabled services
+ const debuggerEnabled = config.services.debugger.enabled;
+ const agentRunnerEnabled = config.services.agentRunner.enabled;
+ const embodimentEnabled = config.services.embodiment.enabled;
+
+ // Smart routing: Multiple services with intelligent request routing
+ if (
+ config.routing.strategy === "smart" &&
+ debuggerEnabled &&
+ agentRunnerEnabled
+ ) {
+ console.log("Using smart router for intelligent request routing");
+
+ const smartRouter = createConfiguredSmartRouter(
+ {
+ debugger: {
+ agentLoader: debuggerAgentLoader,
+ processAgentRequest: debuggerProcessAgentRequest,
+ getDebugSession: debuggerGetDebugSession,
+ createSseConnection: debuggerCreateSseConnection,
+ },
+ agentRunner: {
+ uploadHandler,
+ agentLoader: agentRunnerAgentLoader,
+ processAgentRequest: agentRunnerProcessAgentRequest,
+ },
+ },
+ {
+ enableMetrics: config.server.metrics,
+ enableDebuggerRoutes: debuggerEnabled,
+ }
+ );
+
+ app.use("/", smartRouter);
+ return;
+ }
+
+ // Separate routing: Mount individual routers (extraction-ready)
+ if (
+ config.routing.strategy === "separate" ||
+ config.routing.strategy === "smart"
+ ) {
+ if (debuggerEnabled) {
+ console.log("Mounting debugger router");
+ const debuggerRouter = createDebuggerRouter(
+ debuggerAgentLoader,
+ debuggerProcessAgentRequest,
+ {
+ getDebugSession: debuggerGetDebugSession,
+ createSseConnection: debuggerCreateSseConnection,
+ }
+ );
+ app.use("/", debuggerRouter);
+ }
+
+ if (agentRunnerEnabled) {
+ console.log("Mounting agent-runner router");
+ const agentRunnerRouter = createAgentRunnerRouter(
+ [uploadHandler, agentRunnerAgentLoader],
+ agentRunnerProcessAgentRequest
+ );
+ app.use("/", agentRunnerRouter);
+ }
+
+ // Note: Embodiment router will be mounted here when embodimentEnabled is true
+ // This is where the extraction script will know to include embodiment routes
+ }
+
+ // Legacy routing: Use original individual routers (for backward compatibility)
+ if (config.routing.strategy === "legacy") {
+ console.log("Using legacy routing with original routers");
+
+ if (debuggerEnabled) {
+ import("@debugger/routes/agent/routes").then(
+ ({ default: debuggerRouter }) => {
+ app.use("/", debuggerRouter);
+ }
+ );
+ }
+
+ if (agentRunnerEnabled) {
+ import("@agent-runner/routes/agent/router").then(
+ ({ default: agentRunnerRouter }) => {
+ app.use("/", agentRunnerRouter);
+ }
+ );
+ }
+ }
+}
+
+/**
+ * Configuration helpers for different deployment scenarios
+ * These will be used by the extraction script
+ */
+
+// For backward compatibility - these functions now return RuntimeConfig
+export function createDebuggerServerConfig(): RuntimeConfig {
+ return {
+ serverType: "debugger",
+ services: {
+ debugger: { enabled: true, standalone: true },
+ agentRunner: { enabled: false, standalone: false },
+ embodiment: { enabled: false, standalone: false },
+ },
+ routing: { strategy: "separate" },
+ server: {
+ port: parseInt(process.env.PORT || "5001"),
+ name: "smythos-debugger-server",
+ healthCheck: true,
+ metrics: true,
+ },
+ features: {
+ smartRouting: false,
+ requestTracing: true,
+ circuitBreaker: false,
+ rateLimiting: false,
+ },
+ };
+}
+
+export function createAgentRunnerServerConfig(): RuntimeConfig {
+ return {
+ serverType: "agent-runner",
+ services: {
+ debugger: { enabled: false, standalone: false },
+ agentRunner: { enabled: true, standalone: true },
+ embodiment: { enabled: false, standalone: false },
+ },
+ routing: { strategy: "separate" },
+ server: {
+ port: parseInt(process.env.PORT || "5002"),
+ name: "smythos-agent-runner-server",
+ healthCheck: true,
+ metrics: true,
+ },
+ features: {
+ smartRouting: false,
+ requestTracing: true,
+ circuitBreaker: true,
+ rateLimiting: true,
+ },
+ };
+}
+
+export function createEmbodimentServerConfig(): RuntimeConfig {
+ return {
+ serverType: "embodiment",
+ services: {
+ debugger: { enabled: false, standalone: false },
+ agentRunner: { enabled: false, standalone: false },
+ embodiment: { enabled: true, standalone: true },
+ },
+ routing: { strategy: "separate" },
+ server: {
+ port: parseInt(process.env.PORT || "5003"),
+ name: "smythos-embodiment-server",
+ healthCheck: true,
+ metrics: true,
+ },
+ features: {
+ smartRouting: false,
+ requestTracing: true,
+ circuitBreaker: false,
+ rateLimiting: false,
+ },
+ };
+}
+
+export function createCombinedServerConfig(): RuntimeConfig {
+ return {
+ serverType: "combined",
+ services: {
+ debugger: { enabled: true, standalone: false },
+ agentRunner: { enabled: true, standalone: false },
+ embodiment: { enabled: true, standalone: false },
+ },
+ routing: { strategy: "smart" },
+ server: {
+ port: parseInt(process.env.PORT || "5000"),
+ name: "smythos-runtime-combined",
+ healthCheck: true,
+ metrics: true,
+ },
+ features: {
+ smartRouting: true,
+ requestTracing: true,
+ circuitBreaker: true,
+ rateLimiting: true,
+ },
+ };
+}
diff --git a/packages/runtime/src/core/routing/types.ts b/packages/runtime/src/core/routing/types.ts
new file mode 100644
index 00000000..b4bf13de
--- /dev/null
+++ b/packages/runtime/src/core/routing/types.ts
@@ -0,0 +1,82 @@
+/**
+ * Enterprise-grade routing system types
+ * Following Domain-Driven Design and Clean Architecture principles
+ */
+
+import { Request } from "express";
+
+export interface AgentContext {
+ id: string;
+ version?: string;
+ usingTestDomain: boolean;
+ debugSessionEnabled: boolean;
+ isLocked?: boolean;
+ agentVersion?: string;
+}
+
+export interface RequestContext {
+ correlationId: string;
+ timestamp: number;
+ clientIp: string;
+ userAgent?: string;
+ headers: Record<string, string>;
+}
+
+export interface RoutingDecision {
+ service: 'debugger' | 'agent-runner';
+ reason: string;
+ confidence: number;
+ metadata: Record<string, any>;
+}
+
+export interface ServiceHealth {
+ service: 'debugger' | 'agent-runner';
+ healthy: boolean;
+ lastCheck: number;
+ responseTime?: number;
+ errorRate?: number;
+}
+
+export interface RoutingMetrics {
+ totalRequests: number;
+ debuggerRequests: number;
+ agentRunnerRequests: number;
+ errors: number;
+ averageResponseTime: number;
+}
+
+export interface AgentRequestProcessor {
+ name: string;
+ canHandle(agent: AgentContext, request: RequestContext): Promise<boolean>;
+ process(agent: AgentContext, req: Request): Promise<ProcessingResult>;
+ healthCheck(): Promise<ServiceHealth>;
+}
+
+export interface ProcessingResult {
+ status: number;
+ data: any;
+ metadata?: {
+ processingTime: number;
+ service: string;
+ correlationId: string;
+ };
+}
+
+export interface RoutingStrategy {
+ decide(agent: AgentContext, request: RequestContext): Promise<RoutingDecision>;
+}
+
+export interface CircuitBreakerConfig {
+ failureThreshold: number;
+ resetTimeout: number;
+ monitoringPeriod: number;
+}
+
+export interface RoutingConfig {
+ enableMetrics: boolean;
+ enableCircuitBreaker: boolean;
+ circuitBreakerConfig: CircuitBreakerConfig;
+ healthCheckInterval: number;
+ requestTimeout: number;
+ maxRetries: number;
+}
diff --git a/packages/runtime/src/core/runtime-config.ts b/packages/runtime/src/core/runtime-config.ts
new file mode 100644
index 00000000..617e97e5
--- /dev/null
+++ b/packages/runtime/src/core/runtime-config.ts
@@ -0,0 +1,221 @@
+/**
+ * Runtime Configuration System
+ * Designed for future server extraction without code changes
+ */
+
+export interface RuntimeConfig {
+ // Server identity - determines which services this instance provides
+ serverType: "combined" | "debugger" | "agent-runner" | "embodiment";
+
+ // Service enablement flags
+ services: {
+ debugger: {
+ enabled: boolean;
+ standalone?: boolean; // When true, only debugger routes are active
+ };
+ agentRunner: {
+ enabled: boolean;
+ standalone?: boolean; // When true, only agent-runner routes are active
+ };
+ embodiment: {
+ enabled: boolean;
+ standalone?: boolean; // When true, only embodiment routes are active
+ };
+ };
+
+ // Routing strategy when multiple services are enabled
+ routing: {
+ strategy: "smart" | "separate" | "legacy";
+ // Smart: Intelligent routing based on request characteristics
+ // Separate: Mount separate routers (current approach)
+ // Legacy: Use original individual routers
+ };
+
+ // Server-specific configurations
+ server: {
+ port: number;
+ name: string;
+ healthCheck: boolean;
+ metrics: boolean;
+ };
+
+ // Feature flags for gradual rollout
+ features: {
+ smartRouting: boolean;
+ requestTracing: boolean;
+ circuitBreaker: boolean;
+ rateLimiting: boolean;
+ };
+}
+
+/**
+ * Predefined configurations for different deployment scenarios
+ */
+export const RuntimeConfigs = {
+ // Combined server (current default)
+ combined: (): RuntimeConfig => ({
+ serverType: "combined",
+ services: {
+ debugger: { enabled: true, standalone: false },
+ agentRunner: { enabled: true, standalone: false },
+ embodiment: { enabled: true, standalone: false },
+ },
+ routing: { strategy: "smart" },
+ server: {
+ port: 5000,
+ name: "smythos-runtime-combined",
+ healthCheck: true,
+ metrics: true,
+ },
+ features: {
+ smartRouting: true,
+ requestTracing: true,
+ circuitBreaker: true,
+ rateLimiting: true,
+ },
+ }),
+
+ // Debugger-only server (for extraction)
+ debugger: (): RuntimeConfig => ({
+ serverType: "debugger",
+ services: {
+ debugger: { enabled: true, standalone: true },
+ agentRunner: { enabled: false, standalone: false },
+ embodiment: { enabled: false, standalone: false },
+ },
+ routing: { strategy: "separate" },
+ server: {
+ port: 5001,
+ name: "smythos-debugger-server",
+ healthCheck: true,
+ metrics: true,
+ },
+ features: {
+ smartRouting: false,
+ requestTracing: true,
+ circuitBreaker: false,
+ rateLimiting: false,
+ },
+ }),
+
+ // Agent-runner-only server (for extraction)
+ agentRunner: (): RuntimeConfig => ({
+ serverType: "agent-runner",
+ services: {
+ debugger: { enabled: false, standalone: false },
+ agentRunner: { enabled: true, standalone: true },
+ embodiment: { enabled: false, standalone: false },
+ },
+ routing: { strategy: "separate" },
+ server: {
+ port: 5002,
+ name: "smythos-agent-runner-server",
+ healthCheck: true,
+ metrics: true,
+ },
+ features: {
+ smartRouting: false,
+ requestTracing: true,
+ circuitBreaker: true,
+ rateLimiting: true,
+ },
+ }),
+
+ // Embodiment-only server (for extraction)
+ embodiment: (): RuntimeConfig => ({
+ serverType: "embodiment",
+ services: {
+ debugger: { enabled: false, standalone: false },
+ agentRunner: { enabled: false, standalone: false },
+ embodiment: { enabled: true, standalone: true },
+ },
+ routing: { strategy: "separate" },
+ server: {
+ port: 5003,
+ name: "smythos-embodiment-server",
+ healthCheck: true,
+ metrics: true,
+ },
+ features: {
+ smartRouting: false,
+ requestTracing: true,
+ circuitBreaker: false,
+ rateLimiting: false,
+ },
+ }),
+};
+
+/**
+ * Load configuration from environment or config file
+ * This will be used by the extraction script
+ */
+export function loadRuntimeConfig(): RuntimeConfig {
+ const configType = process.env.SMYTHOS_SERVER_TYPE || "combined";
+
+ switch (configType) {
+ case "debugger":
+ return RuntimeConfigs.debugger();
+ case "agent-runner":
+ return RuntimeConfigs.agentRunner();
+ case "embodiment":
+ return RuntimeConfigs.embodiment();
+ case "combined":
+ default:
+ return RuntimeConfigs.combined();
+ }
+}
+
+/**
+ * Validate configuration
+ */
+export function validateRuntimeConfig(config: RuntimeConfig): {
+ valid: boolean;
+ errors: string[];
+} {
+ const errors: string[] = [];
+
+ // At least one service must be enabled
+ const enabledServices = Object.values(config.services).filter(
+ (service) => service.enabled
+ );
+ if (enabledServices.length === 0) {
+ errors.push("At least one service must be enabled");
+ }
+
+ // Standalone services should be the only enabled service
+ const standaloneServices = Object.entries(config.services)
+ .filter(([_, service]) => service.standalone)
+ .map(([name, _]) => name);
+
+ if (standaloneServices.length > 1) {
+ errors.push(
+ `Multiple standalone services not allowed: ${standaloneServices.join(
+ ", "
+ )}`
+ );
+ }
+
+ if (standaloneServices.length === 1) {
+ const otherEnabledServices = Object.entries(config.services)
+ .filter(([name, service]) => service.enabled && !service.standalone)
+ .map(([name, _]) => name);
+
+ if (otherEnabledServices.length > 0) {
+ errors.push(
+ `Standalone service cannot coexist with other services: ${otherEnabledServices.join(
+ ", "
+ )}`
+ );
+ }
+ }
+
+ // Smart routing requires multiple services
+ if (config.routing.strategy === "smart" && enabledServices.length < 2) {
+ errors.push("Smart routing requires multiple enabled services");
+ }
+
+ return {
+ valid: errors.length === 0,
+ errors,
+ };
+}
diff --git a/packages/runtime/src/core/shared-agent-router.ts b/packages/runtime/src/core/shared-agent-router.ts
new file mode 100644
index 00000000..2d146561
--- /dev/null
+++ b/packages/runtime/src/core/shared-agent-router.ts
@@ -0,0 +1,121 @@
+import { Logger } from "@smythos/sre";
+import express from "express";
+
+export interface AgentRouterConfig {
+ mode: "debugger" | "agent-runner";
+ middlewares: express.RequestHandler[];
+ processAgentRequest: (agentOrId: any, req: express.Request) => Promise<any>;
+ additionalRoutes?: (router: express.Router) => void;
+ loggerPrefix?: string;
+}
+
+/**
+ * Creates a shared agent router that can be configured for both debugger and agent-runner modes
+ * This allows code reuse while maintaining the ability to extract servers separately
+ */
+export function createAgentRouter(config: AgentRouterConfig): express.Router {
+ const console = Logger(config.loggerPrefix || "[Shared] Router: Agent");
+ const router = express.Router();
+
+ // Add any additional routes specific to the mode (e.g., debugger's /debugSession and /monitor)
+ if (config.additionalRoutes) {
+ config.additionalRoutes(router);
+ }
+
+ // Common API routes with configurable middleware and processing
+ const apiRoutes = [
+ { method: "post", path: "/api/*" },
+ { method: "get", path: "/api/*" },
+ { method: "post", path: "/:version/api/*" },
+ { method: "get", path: "/:version/api/*" },
+ { method: "post", path: /^\/v[0-9]+(\.[0-9]+)?\/api\/(.+)/ },
+ ];
+
+ apiRoutes.forEach(({ method, path }) => {
+ router[method](path, config.middlewares, async (req: any, res) => {
+ try {
+ const agent = req._agent;
+ if (!agent) {
+ return res.status(404).json({ error: "Agent not found" });
+ }
+
+ // Handle different function signatures based on mode
+ let result: any;
+ if (config.mode === "debugger") {
+ // Debugger mode: pass agent.id as first parameter
+ result = await config.processAgentRequest(agent.id, req);
+ } else {
+ // Agent-runner mode: pass agent object as first parameter
+ result = await config.processAgentRequest(agent, req);
+ }
+
+ return res.status(result?.status || 500).send(result?.data);
+ } catch (error) {
+ console.error("Error processing agent request:", error);
+ return res.status(500).json({ error: "Internal Server Error" });
+ }
+ });
+ });
+
+ return router;
+}
+
+/**
+ * Factory function to create debugger-specific router
+ */
+export function createDebuggerRouter(
+ agentLoader: express.RequestHandler,
+ processAgentRequest: (agentId: string, req: express.Request) => Promise<any>,
+ additionalServices?: {
+ getDebugSession: (id: string) => any;
+ createSseConnection: (req: any) => string;
+ }
+): express.Router {
+ return createAgentRouter({
+ mode: "debugger",
+ middlewares: [agentLoader],
+ processAgentRequest,
+ loggerPrefix: "[Debugger] Router: Agent",
+ additionalRoutes: (router) => {
+ if (additionalServices) {
+ // Debug session route
+ router.get("/agent/:id/debugSession", (req, res) => {
+ console.log(
+ `Getting debug session for agent ${req.params.id} with client IP ${req.headers["x-forwarded-for"]} - ${req.socket.remoteAddress}. x-hash-id ${req.headers["x-hash-id"]}`
+ );
+ const dbgSession = additionalServices.getDebugSession(req.params.id);
+ res.send({ dbgSession });
+ });
+
+ // Monitor route (SSE)
+ router.get("/agent/:id/monitor", (req, res) => {
+ const sseId = additionalServices.createSseConnection(req);
+
+ // Set headers for SSE
+ res.setHeader("Content-Type", "text/event-stream");
+ res.setHeader("Cache-Control", "no-cache");
+ res.setHeader("Connection", "keep-alive");
+
+ // Send the unique ID as the first event
+ res.write(`event: init\n`);
+ res.write(`data: ${sseId}\n\n`);
+ });
+ }
+ },
+ });
+}
+
+/**
+ * Factory function to create agent-runner-specific router
+ */
+export function createAgentRunnerRouter(
+ middlewares: express.RequestHandler[],
+ processAgentRequest: (agent: any, req: express.Request) => Promise<any>
+): express.Router {
+ return createAgentRouter({
+ mode: "agent-runner",
+ middlewares,
+ processAgentRequest,
+ loggerPrefix: "(Agent Runner) Router: Agent",
+ });
+}
diff --git a/packages/runtime/src/core/smart-agent-router.ts b/packages/runtime/src/core/smart-agent-router.ts
new file mode 100644
index 00000000..7be9532e
--- /dev/null
+++ b/packages/runtime/src/core/smart-agent-router.ts
@@ -0,0 +1,360 @@
+/**
+ * Smart Agent Router - Intelligently routes between debugger and agent-runner
+ * Based on request characteristics and agent properties
+ */
+
+import { Logger } from "@smythos/sre";
+import express from "express";
+import { v4 as uuidv4 } from "uuid";
+
+const console = Logger("[Smart Agent Router]");
+
+export interface RouterDependencies {
+ // Debugger dependencies
+ debugger: {
+ agentLoader: express.RequestHandler;
+ processAgentRequest: (
+ agentId: string,
+ req: express.Request
+ ) => Promise<any>;
+ getDebugSession: (id: string) => any;
+ createSseConnection: (req: any) => string;
+ };
+ // Agent-runner dependencies
+ agentRunner: {
+ uploadHandler: express.RequestHandler;
+ agentLoader: express.RequestHandler;
+ processAgentRequest: (agent: any, req: express.Request) => Promise<any>;
+ };
+}
+
+/**
+ * Determines which service should handle the request based on explicit headers
+ * This provides stable, predictable routing that doesn't depend on domain names
+ *
+ * ROUTING PRIORITY (highest to lowest):
+ * 1. X-FORCE-AGENT-RUNNER: Forces agent-runner (overrides everything)
+ * 2. Debug headers: Forces debugger (X-DEBUG-*, X-MONITOR-ID)
+ * 3. X-FORCE-DEBUGGER: Forces debugger
+ * 4. Deployed versions: Always use agent-runner for production safety
+ * 5. X-ROUTING-MODE: Explicit mode selection (debugger|agent-runner)
+ * 6. Default: agent-runner (production-safe fallback)
+ *
+ * USAGE EXAMPLES:
+ * - Test agent-runner from localhost: Add header "X-FORCE-AGENT-RUNNER: true"
+ * - Test debugger from production: Add header "X-FORCE-DEBUGGER: true"
+ * - Debug session: Add any X-DEBUG-* header (e.g., "X-DEBUG-RUN: true")
+ * - Default behavior: No headers = agent-runner (safe for production)
+ */
+function shouldUseDebugger(req: any): { useDebugger: boolean; reason: string } {
+ const agent = req._agent;
+
+ if (!agent) {
+ return { useDebugger: false, reason: "No agent context" };
+ }
+
+ // 1. Check for explicit agent-runner header (highest priority)
+ const forceAgentRunner = req.header("X-FORCE-AGENT-RUNNER") !== undefined;
+ if (forceAgentRunner) {
+ return {
+ useDebugger: false,
+ reason: "X-FORCE-AGENT-RUNNER header present",
+ };
+ }
+
+ // 2. Check for debug headers (second highest priority)
+ const debugHeaders = [
+ "X-DEBUG-RUN",
+ "X-DEBUG-READ",
+ "X-DEBUG-INJ",
+ "X-DEBUG-STOP",
+ "X-DEBUG-SKIP",
+ "X-MONITOR-ID",
+ ];
+
+ const hasDebugHeader = debugHeaders.some(
+ (header) => req.header(header) !== undefined
+ );
+
+ if (hasDebugHeader) {
+ return { useDebugger: true, reason: "Debug headers present" };
+ }
+
+ // 3. Check for explicit debugger header
+ const forceDebugger = req.header("X-FORCE-DEBUGGER") !== undefined;
+ if (forceDebugger) {
+ return { useDebugger: true, reason: "X-FORCE-DEBUGGER header present" };
+ }
+
+ // 4. Check if it's a deployed version (production) - always use agent-runner
+ const isDeployedVersion =
+ agent.agentVersion &&
+ agent.agentVersion !== "development" &&
+ agent.agentVersion !== "latest";
+
+ if (isDeployedVersion) {
+ return {
+ useDebugger: false,
+ reason: `Deployed version: ${agent.agentVersion}`,
+ };
+ }
+
+ // 5. Default routing based on explicit mode header
+ const routingMode = req.header("X-ROUTING-MODE");
+ if (routingMode === "debugger") {
+ return { useDebugger: true, reason: "X-ROUTING-MODE: debugger" };
+ }
+ if (routingMode === "agent-runner") {
+ return { useDebugger: false, reason: "X-ROUTING-MODE: agent-runner" };
+ }
+
+ // 6. Final fallback: Default to agent-runner for production safety
+ // This ensures that without explicit headers, we always use the production-safe route
+ return {
+ useDebugger: false,
+ reason: "Default production-safe routing (no explicit routing headers)",
+ };
+}
+
+/**
+ * Creates a smart router that automatically chooses between debugger and agent-runner
+ */
+export function createSmartAgentRouter(
+ dependencies: RouterDependencies
+): express.Router {
+ const router = express.Router();
+
+ // Add correlation ID for request tracing
+ router.use((req: any, res, next) => {
+ if (!req.headers["x-correlation-id"]) {
+ req.headers["x-correlation-id"] = uuidv4();
+ }
+ res.setHeader("x-correlation-id", req.headers["x-correlation-id"]);
+ next();
+ });
+
+ // Debugger-specific routes (always use debugger)
+ router.get("/agent/:id/debugSession", async (req, res) => {
+ try {
+ const dbgSession = dependencies.debugger.getDebugSession(req.params.id);
+ res.send({ dbgSession });
+ } catch (error) {
+ console.error("Debug session error:", error);
+ res.status(500).json({ error: "Debug session unavailable" });
+ }
+ });
+
+ router.get("/agent/:id/monitor", async (req, res) => {
+ try {
+ const sseId = dependencies.debugger.createSseConnection(req);
+
+ res.setHeader("Content-Type", "text/event-stream");
+ res.setHeader("Cache-Control", "no-cache");
+ res.setHeader("Connection", "keep-alive");
+
+ res.write(`event: init\n`);
+ res.write(`data: ${sseId}\n\n`);
+ } catch (error) {
+ console.error("Monitor error:", error);
+ res.status(500).json({ error: "Monitor unavailable" });
+ }
+ });
+
+ // Smart middleware that chooses the right service
+ const smartMiddleware = async (req: any, res: express.Response) => {
+ const correlationId = req.headers["x-correlation-id"];
+ const startTime = Date.now();
+
+ try {
+ // Step 1: Load agent context using combined middleware approach
+ await runMiddleware(req, res, dependencies.agentRunner.uploadHandler);
+ await runMiddleware(req, res, dependencies.debugger.agentLoader);
+
+ // Step 2: Make routing decision
+ const { useDebugger, reason } = shouldUseDebugger(req);
+
+ console.log(
+ `Routing decision: ${
+ useDebugger ? "DEBUGGER" : "AGENT-RUNNER"
+ } - ${reason}`,
+ {
+ correlationId,
+ agentId: req._agent?.id,
+ path: req.path,
+ }
+ );
+
+ // Step 3: Process with appropriate service
+ let result: any;
+
+ if (useDebugger) {
+ result = await dependencies.debugger.processAgentRequest(
+ req._agent.id,
+ req
+ );
+ } else {
+ result = await dependencies.agentRunner.processAgentRequest(
+ req._agent,
+ req
+ );
+ }
+
+ // Step 4: Send response
+ const processingTime = Date.now() - startTime;
+ console.debug(`Request completed`, {
+ correlationId,
+ service: useDebugger ? "debugger" : "agent-runner",
+ status: result?.status || 200,
+ processingTime,
+ });
+
+ return res.status(result?.status || 200).send(result?.data || result);
+ } catch (error) {
+ const processingTime = Date.now() - startTime;
+ console.error(`Request failed`, {
+ correlationId,
+ error: error.message,
+ processingTime,
+ });
+
+ return res.status(500).json({
+ error: "Internal Server Error",
+ correlationId,
+ timestamp: new Date().toISOString(),
+ });
+ }
+ };
+
+ // Common API routes
+ const apiRoutes = [
+ { method: "post", path: "/api/*" },
+ { method: "get", path: "/api/*" },
+ { method: "post", path: "/:version/api/*" },
+ { method: "get", path: "/:version/api/*" },
+ { method: "post", path: /^\/v[0-9]+(\.[0-9]+)?\/api\/(.+)/ },
+ ];
+
+ apiRoutes.forEach(({ method, path }) => {
+ router[method](path, smartMiddleware);
+ });
+
+ return router;
+}
+
+/**
+ * Helper function to promisify Express middleware
+ */
+function runMiddleware(
+ req: any,
+ res: express.Response,
+ middleware: express.RequestHandler
+): Promise<void> {
+ return new Promise((resolve, reject) => {
+ middleware(req, res, (err) => {
+ if (err) reject(err);
+ else resolve();
+ });
+ });
+}
+
+/**
+ * Configuration helper for different deployment scenarios
+ */
+export interface SmartRouterConfig {
+ enableDebuggerRoutes?: boolean;
+ enableMetrics?: boolean;
+ logLevel?: "debug" | "info" | "warn" | "error";
+}
+
+export function createConfiguredSmartRouter(
+ dependencies: RouterDependencies,
+ config: SmartRouterConfig = {}
+): express.Router {
+ const router = createSmartAgentRouter(dependencies);
+
+ // Add health check endpoint
+ router.get("/health/smart-router", (req, res) => {
+ res.json({
+ status: "healthy",
+ timestamp: new Date().toISOString(),
+ version: "1.0.0",
+ });
+ });
+
+ // Add metrics endpoint if enabled
+ if (config.enableMetrics) {
+ let requestCount = 0;
+ let debuggerCount = 0;
+ let agentRunnerCount = 0;
+
+ router.use((req: any, res, next) => {
+ requestCount++;
+
+ res.on("finish", () => {
+ // This is a simple way to track which service was used
+ // In a real implementation, you'd want more sophisticated metrics
+ const userAgent = req.headers["user-agent"] || "";
+ if (userAgent.includes("debug")) {
+ debuggerCount++;
+ } else {
+ agentRunnerCount++;
+ }
+ });
+
+ next();
+ });
+
+ router.get("/metrics/smart-router", (req, res) => {
+ res.json({
+ totalRequests: requestCount,
+ debuggerRequests: debuggerCount,
+ agentRunnerRequests: agentRunnerCount,
+ timestamp: new Date().toISOString(),
+ });
+ });
+ }
+
+ return router;
+}
+
+/**
+ * Utility function to test routing decisions without making actual requests
+ * Useful for debugging and testing the routing logic
+ */
+export function testRoutingDecision(
+ agentContext: any,
+ headers: Record<string, string> = {}
+): { useDebugger: boolean; reason: string } {
+ const mockReq = {
+ _agent: agentContext,
+ header: (name: string) => headers[name],
+ };
+
+ return shouldUseDebugger(mockReq);
+}
+
+/**
+ * Helper function to create common header combinations for testing
+ */
+export const RoutingHeaders = {
+ // Force agent-runner (highest priority)
+ FORCE_AGENT_RUNNER: { "X-FORCE-AGENT-RUNNER": "true" },
+
+ // Force debugger
+ FORCE_DEBUGGER: { "X-FORCE-DEBUGGER": "true" },
+
+ // Debug session headers
+ DEBUG_RUN: { "X-DEBUG-RUN": "true" },
+ DEBUG_STOP: { "X-DEBUG-STOP": "true" },
+ DEBUG_READ: { "X-DEBUG-READ": "true" },
+ DEBUG_INJ: { "X-DEBUG-INJ": "true" },
+ DEBUG_SKIP: { "X-DEBUG-SKIP": "true" },
+ MONITOR: { "X-MONITOR-ID": "test-monitor" },
+
+ // Explicit routing mode
+ MODE_DEBUGGER: { "X-ROUTING-MODE": "debugger" },
+ MODE_AGENT_RUNNER: { "X-ROUTING-MODE": "agent-runner" },
+
+ // No headers (default behavior)
+ NONE: {},
+};
diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.ts
index 0f02c977..ffad44a0 100644
--- a/packages/runtime/src/index.ts
+++ b/packages/runtime/src/index.ts
@@ -29,12 +29,16 @@ import { SmythOSSManagedVault } from "@core/connectors/SmythOSSManagedVault.clas
import { SmythOSSVault } from "@core/connectors/SmythOSSVault.class";
// Debugger Imports
-import agentRouter from "@debugger/routes/agent/routes";
import modelsRouter from "@debugger/routes/models/router";
// Agent-runner imports
-// import agentRouter from "@agent-runner/routes/agent/router";
-// import oauthRouter from "@agent-runner/routes/_oauth/router";
+import oauthRouter from "@agent-runner/routes/_oauth/router";
+
+// Shared router configuration
+import {
+ configureAgentRouters,
+ createCombinedServerConfig,
+} from "@core/router-config";
// Embodiment imports
import { routes as embodimentRoutes } from "@embodiment/routes";
@@ -373,11 +377,14 @@ app.get("/", (req: any, res) => {
res.send(`SmythOS Runtime Server`);
});
-app.use("/", agentRouter);
+// Configure agent routers using shared implementation
+configureAgentRouters(app, createCombinedServerConfig());
+
+app.use("/", embodimentRoutes);
+
app.use("/models", modelsRouter);
-// app.use("/oauth", oauthRouter);
+app.use("/oauth", oauthRouter);
app.use("/swagger", swaggerUi.serve);
-app.use("/", embodimentRoutes);
// 404 handler - must come before error handler
app.use(notFoundHandler);
diff --git a/packages/runtime/src/modules/agent-runner/config.ts b/packages/runtime/src/modules/agent-runner/config.ts
new file mode 100644
index 00000000..60d0cd4a
--- /dev/null
+++ b/packages/runtime/src/modules/agent-runner/config.ts
@@ -0,0 +1,34 @@
+import dotenv from 'dotenv';
+dotenv.config();
+
+const config = {
+ env: {
+ ADMIN_PORT: process.env.ADMIN_PORT || 8080,
+
+ BASE_URL: process.env.BASE_URL,
+ SMYTH_API_BASE_URL: process.env.SMYTH_API_SERVER,
+
+ LOGTO_SERVER: process.env.LOGTO_SERVER,
+ LOGTO_API_RESOURCE: process.env.LOGTO_API_RESOURCE,
+ LOGTO_M2M_APP_ID: process.env.LOGTO_M2M_APP_ID,
+ LOGTO_M2M_APP_SECRET: process.env.LOGTO_M2M_APP_SECRET,
+
+ NODE_ENV: process.env?.NODE_ENV,
+
+ AGENT_DOMAIN: process.env?.AGENT_DOMAIN,
+ PROD_AGENT_DOMAIN: process.env?.PROD_AGENT_DOMAIN,
+ AGENT_DOMAIN_PORT: process.env?.AGENT_DOMAIN_PORT,
+
+ REDIS_SENTINEL_HOSTS: process.env?.REDIS_SENTINEL_HOSTS || '',
+ REDIS_MASTER_NAME: process.env?.REDIS_MASTER_NAME,
+ REDIS_PASSWORD: process.env?.REDIS_PASSWORD,
+
+ REQ_LIMIT_PER_SECOND: process.env.REQ_LIMIT_PER_SECOND || 30,
+ REQ_LIMIT_PER_MINUTE: process.env.REQ_LIMIT_PER_MINUTE || 300,
+ REQ_LIMIT_PER_HOUR: process.env.REQ_LIMIT_PER_HOUR || 10000,
+ MAX_LATENCY_FREE_USER: process.env.MAX_LATENCY_FREE_USER || 100,
+ MAX_LATENCY_PAID_USER: process.env.MAX_LATENCY_PAID_USER || 10,
+ },
+};
+
+export default config;
diff --git a/packages/runtime/src/modules/agent-runner/constants.ts b/packages/runtime/src/modules/agent-runner/constants.ts
new file mode 100644
index 00000000..4dde3303
--- /dev/null
+++ b/packages/runtime/src/modules/agent-runner/constants.ts
@@ -0,0 +1,78 @@
+import os from 'os';
+
+// supported request methods
+export const REQUEST_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
+
+export const REQUEST_CONTENT_TYPES = {
+ none: 'none',
+ urlEncodedFormData: 'application/x-www-form-urlencoded',
+ multipartFormData: 'multipart/form-data',
+ json: 'application/json',
+ text: 'text/plain',
+ xml: 'application/xml',
+ binary: 'binary',
+};
+
+export enum EMBODIMENT_TYPES {
+ ChatBot = 'chatBot',
+ ChatGPT = 'chatGPT',
+}
+
+export const ERR_MSG_INVALID_IMAGE_SOURCE =
+ 'Please provide a valid Image Source. Supported image sources are: HTTP(S) URL, Base64 string, Data URL, Output Image from other component(s).';
+export const ERR_MSG_INVALID_BINARY =
+ 'Please provide a valid data that is either a Blob, SmythFileObject (Binary Output from any Component), ArrayBuffer, Buffer, Base64 string, Data URL, or HTTP(s) URL';
+export const ERR_MSG_MAX_DEPTH = 'The maximum depth has been exceeded for the provided array or object.';
+export const ERR_MSG_MAX_ARRAY_SIZE = 'The maximum array size has been exceeded for the provided array.';
+export const ERR_MSG_MAX_OBJECT_SIZE = 'The maximum object size has been exceeded for the provided object.';
+
+export const MAX_DEPTH = 10;
+export const MAX_OBJECT_SIZE = 1000;
+export const MAX_ARRAY_SIZE = 1000;
+
+export const MAX_FILE_SIZE = 20 * 1024 * 1024; // 10MB
+
+export const MAX_FILE_COUNT = 10;
+
+// Default maximum number of tokens allowed for LLM
+export const DEFAULT_MAX_TOKENS_FOR_LLM = 2048;
+
+// life cycle tag for daily purge of s3 objects
+export const S3_DAILY_PURGE_LIFECYCLE_TAG = 'ExpirationPolicy=DeleteDaily';
+export const S3_WEEKLY_PURGE_LIFECYCLE_TAG = 'ExpirationPolicy=DeleteWeekly';
+export const S3_MONTHLY_PURGE_LIFECYCLE_TAG = 'ExpirationPolicy=DeleteMonthly';
+
+export const TOOL_USE_DEFAULT_MODEL = 'gpt-3.5-turbo';
+
+export const COMP_NAMES = {
+ apiCall: 'APICall',
+ code: 'Code',
+ llmPrompt: 'PromptGenerator',
+ visionLLM: 'VisionLLM',
+};
+
+export const JSON_RESPONSE_INSTRUCTION =
+ '\nAll responses should be in valid JSON format, compacted without newlines, indentations, or additional JSON syntax markers.';
+
+export const DEFAULT_FILE_PARSING_ENDPOINT = '/api/process_attachment_fallback';
+
+export const MODELS_FOR_LEGACY_USERS = [
+ 'gpt-4o-mini',
+ 'gpt-4.1-nano',
+ 'gpt-4.1-mini',
+ 'gpt-4.1',
+ 'gpt-4.5-preview',
+ 'gpt-4o',
+ 'o4-mini',
+ 'o3',
+ 'o3-mini',
+ 'o1',
+ 'o1-mini',
+ 'o1-preview',
+ 'gpt-4-turbo-latest',
+ 'gpt-4-turbo',
+ 'gpt-4-latest',
+ 'gpt-4',
+ 'gpt-3.5-turbo-latest',
+ 'gpt-3.5-turbo',
+];
diff --git a/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/index.ts b/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/index.ts
index 1a55b52f..6422c9f8 100644
--- a/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/index.ts
+++ b/packages/runtime/src/modules/agent-runner/middlewares/agent-oauth.mw/index.ts
@@ -1,11 +1,13 @@
import { NextFunction, Response } from "express";
+
+import { Logger } from "@smythos/sre";
+
+import { getAgentAuthData } from "@core/helpers/agent.helper";
+
import BearerMWFactory from "./bearer";
import OIDCMWFactory from "./oidc";
-import { getAgentAuthData } from "../../../../core/helpers/agent.helper";
-import { createLogger } from "../../../../core/services/logger";
-
-const console = createLogger("___FILENAME___");
+const console = Logger("(Agent Runner) Middleware: Agent OAuth");
//this maps to agent.auth.provider entry, the selected provider is stored in agent.auth.method
const providers = {
diff --git a/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts b/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts
index f2cace2a..02d2cad8 100644
--- a/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts
+++ b/packages/runtime/src/modules/agent-runner/middlewares/agentLoader.mw.ts
@@ -1,17 +1,16 @@
-import config from "../config";
+import { ConnectorService } from "@smythos/sre";
+
+import { DEFAULT_FILE_PARSING_ENDPOINT } from "@agent-runner/constants";
+import config from "@core/config";
+
import {
addDefaultComponentsAndConnections,
extractAgentVerionsAndPath,
getAgentDomainById,
-} from "../services/agent-helper";
-
-import { ConnectorService } from "@smythos/sre";
-import { DEFAULT_FILE_PARSING_ENDPOINT } from "../constants";
-import { createLogger } from "../services/logger";
-
-import { refreshBillingCache } from "../services/billing-service";
+} from "@core/helpers/agent.helper";
+import { Logger } from "@smythos/sre";
-const console = createLogger("___FILENAME___");
+const console = Logger("(Agent Runner) Middleware: Agent Loader");
export default async function agentLoader(req, res, next) {
console.log("agentLoader", req.path);
@@ -115,15 +114,6 @@ export default async function agentLoader(req, res, next) {
req._agent.usingTestDomain = isTestDomain;
req._agent.domain = agentDomain || (await getAgentDomainById(agentId));
- //req._agent.version = version;
- //req._data1 = 1;
-
- // Pre-fetch billing data to ensure cached data is readily available for usage limit validation
- // To avoid an additional network call in this middleware, we pass teamId to refreshBillingCache
- // The parentTeamId is then derived from the teamId within refreshBillingCache.
- const parentTeamId = agentData.data?.parentTeamId;
- const teamId = agentData.data?.teamId;
- refreshBillingCache(parentTeamId, teamId);
console.log(
`Loaded Agent:${agentId} v=${version} path=${path} isTestDomain=${isTestDomain} domain=${agentDomain}`
diff --git a/packages/runtime/src/modules/agent-runner/middlewares/bearer.ts b/packages/runtime/src/modules/agent-runner/middlewares/bearer.ts
deleted file mode 100644
index 354cc00f..00000000
--- a/packages/runtime/src/modules/agent-runner/middlewares/bearer.ts
+++ /dev/null
@@ -1,25 +0,0 @@
-import { NextFunction, Request, Response } from 'express';
-import axios from 'axios';
-import qs from 'qs';
-
-const mwFactory = (config: any) => {
- // Middleware to validate an access token using the token introspection endpoint
- const validateTokenMiddleware = async (req: Request, res: Response, next: NextFunction) => {
- // Extract the token from the request header or URL query
- const token = req.headers['authorization']?.split(' ')[1] || req.query.token;
-
- if (!token) {
- return res.status(401).json({ error: 'Access token is required' });
- }
-
- if (token == config.token) {
- next();
- } else {
- // Token is not active
- res.status(401).json({ error: 'Invalid access token' });
- }
- };
- return validateTokenMiddleware;
-};
-
-export default mwFactory;
diff --git a/packages/runtime/src/modules/agent-runner/middlewares/index.ts b/packages/runtime/src/modules/agent-runner/middlewares/index.ts
index 7ce9f7a4..45f994fa 100644
--- a/packages/runtime/src/modules/agent-runner/middlewares/index.ts
+++ b/packages/runtime/src/modules/agent-runner/middlewares/index.ts
@@ -1,11 +1,13 @@
import { NextFunction, Response } from "express";
-import BearerMWFactory from "./bearer";
-import OIDCMWFactory from "./oidc";
-import { getAgentAuthData } from "../../../core/helpers/agent.helper";
-import { createLogger } from "../../../core/services/logger";
+import { Logger } from "@smythos/sre";
-const console = createLogger("___FILENAME___");
+import { getAgentAuthData } from "@core/helpers/agent.helper";
+
+import BearerMWFactory from "./agent-oauth.mw/bearer";
+import OIDCMWFactory from "./agent-oauth.mw/oidc";
+
+const console = Logger("(Agent Runner) Middleware: Index");
//this maps to agent.auth.provider entry, the selected provider is stored in agent.auth.method
const providers = {
diff --git a/packages/runtime/src/modules/agent-runner/middlewares/oidc.ts b/packages/runtime/src/modules/agent-runner/middlewares/oidc.ts
deleted file mode 100644
index 16abe8f7..00000000
--- a/packages/runtime/src/modules/agent-runner/middlewares/oidc.ts
+++ /dev/null
@@ -1,309 +0,0 @@
-import { NextFunction, Request, Response } from 'express';
-import axios from 'axios';
-import qs from 'qs';
-import jwt from 'jsonwebtoken';
-import jwksClient from 'jwks-rsa';
-
-function isJWT(token) {
- const parts = token.split('.');
- if (parts.length === 3) {
- try {
- const header = JSON.parse(Buffer.from(parts[0], 'base64').toString('utf8'));
- const payload = JSON.parse(Buffer.from(parts[1], 'base64').toString('utf8'));
-
- // Optionally, check if header contains typical JWT properties
- if (header.alg && header.typ) {
- return true;
- }
- } catch (error) {
- // Errors in parsing mean this isn't a valid JWT
- return false;
- }
- }
- return false; // Not in JWT format if it doesn't have three parts
-}
-
-//FIXME : handle JWT tokens as well
-const mwFactory = async (providerInfo: any, res: Response) => {
- console.log('Agent Auth OIDC');
- const authOIDCConfigURL = providerInfo.OIDCConfigURL;
- const clientID = providerInfo.clientID;
- const clientSecret = providerInfo.clientSecret;
- const allowedEmails = (providerInfo.allowedEmails || []).filter((e: string) => e.trim());
-
- if (!authOIDCConfigURL || !clientID || !clientSecret) {
- console.log('OIDC:Auth provider not configured');
- return res.status(401).send({ error: 'Auth provider not configured' });
- }
-
- const openid: any = await axios.get(authOIDCConfigURL).catch((error) => ({ error }));
-
- if (openid?.error) {
- console.log('OIDC:Error getting OIDC config');
- return res.status(401).send({ error: 'Error getting OIDC config' });
- }
-
- const config = { openid: openid.data, clientID, clientSecret };
-
- let jwks;
- function getKey(header, callback) {
- jwks.getSigningKey(header.kid, function (err, key: any) {
- const signingKey = key?.publicKey || key?.rsaPublicKey;
- callback(null, signingKey);
- });
- }
-
- // Middleware to validate an opaque access token using the token introspection endpoint
- const validateOpaqueTokenMiddleware = async (token, req: Request) => {
- const auth = {
- username: config.clientID,
- password: config.clientSecret,
- };
- try {
- // Send a POST request to the introspection endpoint
- const response = await axios.post(
- config.openid.introspection_endpoint,
- qs.stringify({
- token: token, // The token you want to introspect
- // Optionally include token_type_hint: 'access_token' if needed
- }),
- {
- // Basic Auth with the client ID and client secret
- auth,
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- },
- );
-
- //console.log('Token introspection response:', config.openid.introspection_endpoint, response.data);
- // The introspection response will contain a boolean "active" field indicating validity
- if (response.data && response.data.active) {
- // Token is valid; you could attach token details to the request object if needed
- const oidc_introspect_data = response.data; // This attaches the token data to the request object
- //console.log('OIDC:Token introspection response:', oidc_introspect_data);
-
- try {
- //TODO : cache this for a short time
- const userInfo = await axios.get(config.openid.userinfo_endpoint, {
- headers: {
- Authorization: `Bearer ${token}`,
- },
- });
-
- //check if the user is allowed
- console.log('OIDC:userinfo', userInfo?.data);
-
- if (allowedEmails.length > 0) {
- const email = userInfo?.data?.email || '';
- const domain = email.split('@')[1];
- if (!allowedEmails.includes(email) && !allowedEmails.includes(domain)) {
- console.log('OIDC:User not allowed', email, domain);
- //the status code should be 403 here, but chatGPT goes in infinite loop if we use it.
- return { error: 'OIDC:User not allowed', status: 200 };
- }
- }
-
- req['_agent_authinfo'] = { userinfo: userInfo?.data };
-
- return { error: null };
- } catch (error) {
- return { error: 'OIDC:userinfo failed', status: 401 };
- }
- } else {
- // Token is not active
- return { error: 'OIDC:Agent Access token is invalid or expired', status: 401 };
- }
- } catch (error) {
- // Handle errors, such as network issues or the introspection endpoint being down
- console.error('Token introspection error:', error);
- return { error: 'OIDC:Internal server error during token validation', status: 500 };
- }
- };
-
- const validateJWTTokenMiddleware = async (token, req: Request) => {
- if (!token) {
- return res.status(401).json({ error: 'Access token is required' });
- }
-
- // Check if token is a JWT
- if (token.split('.').length === 3) {
- // Token is a JWT, validate it
- try {
- const decoded = jwt.verify(token, getKey, {
- algorithms: ['RS256'],
- });
-
- console.log(decoded);
- return { error: null };
- } catch (err) {
- return res.status(401).json({ error: 'Invalid JWT token' });
- }
- } else if (config.openid.introspection_endpoint) {
- // Token is not a JWT, use introspection endpoint
- try {
- const response = await axios.post(
- config.openid.introspection_endpoint,
- qs.stringify({
- token: token,
- }),
- {
- auth: {
- username: config.clientID,
- password: config.clientSecret,
- },
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- },
- );
-
- if (response.data && response.data.active) {
- return { error: null };
- } else {
- return { error: 'Access token is invalid or expired', status: 401 };
- }
- } catch (error) {
- console.error('Token introspection error:', error);
- return { error: 'Internal server error during token validation', status: 500 };
- }
- } else {
- // No suitable method to validate the token
- return { error: 'Unable to validate access token', status: 401 };
- }
- };
-
- const validateTokenMiddleware = async (req: Request, res: Response, next: NextFunction) => {
- const token = req.headers['authorization']?.split(' ')[1] || req.query.token;
- if (!token) {
- console.log('OIDC:Access token is required');
- return res.status(401).json({ error: 'Access token is required' });
- }
-
- const isJWTToken = isJWT(token);
-
- if (isJWTToken) {
- // Set up JWKS client using the JWKS URI from the OpenID configuration
- jwks = jwksClient({
- jwksUri: config.openid.jwks_uri,
- });
- const result: any = await validateJWTTokenMiddleware(token, req);
- if (result.error) {
- console.log('OIDC:JWT validation failed', result.error);
- return res.status(result.status).json({ error: result.error });
- }
- return next();
- } else {
- const result: any = await validateOpaqueTokenMiddleware(token, req);
- if (result.error) {
- console.log('OIDC:Token validation failed', result.error);
- return res.status(result.status).json({ error: result.error });
- }
- return next();
- }
- };
- return validateTokenMiddleware;
-};
-
-export default mwFactory;
-
-//TODO : test below updated code that handles jwt tokens as well
-/*
-import { NextFunction, Request, Response } from 'express';
-import axios from 'axios';
-import qs from 'qs';
-import jwt from 'jsonwebtoken';
-import jwksClient from 'jwks-rsa';
-
-const mwFactory = async (providerInfo: any, res: Response) => {
- const authOIDCConfigURL = providerInfo.OIDCConfigURL;
- const clientID = providerInfo.clientID;
- const clientSecret = providerInfo.clientSecret;
-
- if (!authOIDCConfigURL || !clientID || !clientSecret) {
- return res.status(401).send({ error: 'Auth provider not configured' });
- }
-
- const openid: any = await axios.get(authOIDCConfigURL).catch((error) => ({ error }));
-
- if (openid?.error) {
- return res.status(401).send({ error: 'Error getting OIDC config' });
- }
-
- const config = { openid: openid.data, clientID, clientSecret };
-
- // Set up JWKS client using the JWKS URI from the OpenID configuration
- const jwks = jwksClient({
- jwksUri: config.openid.jwks_uri,
- });
-
- function getKey(header, callback) {
- jwks.getSigningKey(header.kid, function (err, key) {
- var signingKey = key.publicKey || key.rsaPublicKey;
- callback(null, signingKey);
- });
- }
-
- // Middleware to validate an access token using JWT validation or token introspection endpoint
- const validateTokenMiddleware = async (req: Request, res: Response, next: NextFunction) => {
- const token = req.headers['authorization']?.split(' ')[1] || req.query.token;
-
- if (!token) {
- return res.status(401).json({ error: 'Access token is required' });
- }
-
- // Check if token is a JWT
- if (token.split('.').length === 3) {
- // Token is a JWT, validate it
- try {
- const decoded = jwt.verify(token, getKey, {
- algorithms: ['RS256'],
- });
-
- req.user = decoded; // This attaches the token data to the request object
- return next(); // Proceed to the next middleware
- } catch (err) {
- return res.status(401).json({ error: 'Invalid JWT token' });
- }
- } else if (config.openid.introspection_endpoint) {
- // Token is not a JWT, use introspection endpoint
- try {
- const response = await axios.post(
- config.openid.introspection_endpoint,
- qs.stringify({
- token: token,
- }),
- {
- auth: {
- username: config.clientID,
- password: config.clientSecret,
- },
- headers: {
- 'Content-Type': 'application/x-www-form-urlencoded',
- },
- },
- );
-
- if (response.data && response.data.active) {
- req.user = response.data;
- return next();
- } else {
- return res.status(401).json({ error: 'Access token is invalid or expired' });
- }
- } catch (error) {
- console.error('Token introspection error:', error);
- return res.status(500).json({ error: 'Internal server error during token validation' });
- }
- } else {
- // No suitable method to validate the token
- return res.status(401).json({ error: 'Unable to validate access token' });
- }
- };
-
- return validateTokenMiddleware;
-};
-
-export default mwFactory;
-
-
-*/
diff --git a/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts b/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts
index 2af0ef19..9350eda2 100644
--- a/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts
+++ b/packages/runtime/src/modules/agent-runner/routes/_oauth/router.ts
@@ -1,9 +1,11 @@
-import { readAgentOAuthConfig } from "@/core/helpers/agent.helper";
-import agentLoader from "@core/middlewares/agentLoader.mw";
import axios from "axios";
import express, { Request, Response } from "express";
import querystring from "querystring";
+import { readAgentOAuthConfig } from "@core/helpers/agent.helper";
+
+import agentLoader from "@agent-runner/middlewares/agentLoader.mw";
+
const router = express.Router();
router.use(agentLoader);
diff --git a/packages/runtime/src/modules/agent-runner/routes/agent/router.ts b/packages/runtime/src/modules/agent-runner/routes/agent/router.ts
index ac54152a..eae29268 100644
--- a/packages/runtime/src/modules/agent-runner/routes/agent/router.ts
+++ b/packages/runtime/src/modules/agent-runner/routes/agent/router.ts
@@ -1,102 +1,12 @@
-import express from "express";
-import agentLoader from "../../middlewares/agentLoader.mw";
-import cors from "../../middlewares/cors.mw";
-import {
- createSseConnection,
- getDebugSession,
- processAgentRequest,
-} from "../../services/agent-request-handler";
-import uploadHandler from "../../middlewares/uploadHandler.mw";
-import ParallelRequestLimiter from "../../middlewares/ParallelRequestLimiter.mw";
-import { createLogger } from "../../services/logger";
-const console = createLogger("___FILENAME___");
-const router = express.Router();
+import agentLoader from "@agent-runner/middlewares/agentLoader.mw";
+import { processAgentRequest } from "@agent-runner/services/agent-request-handler";
+import { uploadHandler } from "@core/middlewares/uploadHandler.mw";
+import { createAgentRunnerRouter } from "@core/shared-agent-router";
/* agentLoader must come before agentAuth because agentAuth relies on req._agent, set by agentLoader.
Also, uploadHandler should precede agentLoader to parse multipart/form-data correctly */
-const middlewares = [cors, uploadHandler, agentLoader, ParallelRequestLimiter];
+const middlewares = [uploadHandler, agentLoader];
-router.options("*", [cors]); //enable CORS for preflight requests
-
-router.get("/agent/:id/debugSession", [cors], (req, res, next) => {
- console.log(
- `Getting debug session for agent ${req.params.id} with client IP ${req.headers["x-forwarded-for"]} - ${req.socket.remoteAddress}. x-hash-id ${req.headers["x-hash-id"]}`
- );
- const dbgSession = getDebugSession(req.params.id);
- res.send({ dbgSession });
-});
-
-router.get("/agent/:id/monitor", [cors], (req, res, next) => {
- const sseId = createSseConnection(req);
-
- // Set headers for SSE
- res.setHeader("Content-Type", "text/event-stream");
- res.setHeader("Cache-Control", "no-cache");
- res.setHeader("Connection", "keep-alive");
-
- // Send the unique ID as the first event
- res.write(`event: init\n`);
- res.write(`data: ${sseId}\n\n`);
-});
-
-router.post(`/api/*`, middlewares, async (req, res) => {
- const agent = req._agent;
- const result: any = await processAgentRequest(agent.id, req);
- // const result = await sreAdapter.debugRun(agent.id, req);
- return res.status(result?.status || 500).send(result?.data);
-});
-router.get(`/api/*`, middlewares, async (req, res) => {
- const agent: any = req._agent;
- const result: any = await processAgentRequest(agent.id, req);
-
- // const result = await sreAdapter.debugRun(agent.id, req);
- return res.status(result?.status || 500).send(result?.data);
- // return res.status(200).send(result);
-});
-
-router.post(`/:version/api/*`, middlewares, async (req, res) => {
- const agent: any = req._agent;
- const result: any = await processAgentRequest(agent.id, req);
- return res.status(result?.status || 500).send(result?.data);
-});
-router.get(`/:version/api/*`, middlewares, async (req, res) => {
- const agent: any = req._agent;
- const result: any = await processAgentRequest(agent.id, req);
- return res.status(result?.status || 500).send(result?.data);
-});
-
-router.post(
- /^\/v[0-9]+(\.[0-9]+)?\/api\/(.+)/,
- middlewares,
- async (req, res) => {
- const agent: any = req._agent;
- if (!agent) {
- res.status(404).json({ error: "Agent not found" });
- return;
- }
- //const parts = req.url.split('/');
- //const version = parts[1];
- //const endpoint = parts[3];
-
- const result: any = await processAgentRequest(agent.id, req);
- return res.status(result?.status || 500).send(result?.data);
- //res.send({ result: `Not implemented yet\nVersion: ${version}, Endpoint: ${endpoint}` });
- }
-);
-
-// router.post(`/component/:name`, middlewares, async (req, res) => {
-// const { name } = req.params;
-// const component = Components[name];
-// if (!component) {
-// res.status(404).send('Component not found');
-// return;
-// }
-// const result = await component.process(req.body).catch((error) => ({ error }));
-// if (result.error) {
-// res.status(500).send(result);
-// return;
-// }
-// res.send(result);
-// });
+const router = createAgentRunnerRouter(middlewares, processAgentRequest);
export default router;
diff --git a/packages/runtime/src/modules/agent-runner/services/BillingError.class.ts b/packages/runtime/src/modules/agent-runner/services/BillingError.class.ts
new file mode 100644
index 00000000..15fbf081
--- /dev/null
+++ b/packages/runtime/src/modules/agent-runner/services/BillingError.class.ts
@@ -0,0 +1,14 @@
+export class BillingError extends Error {
+ code: string;
+ status: number;
+
+ constructor(message: string, code: string = 'BILLING_LIMIT_REACHED', status: number = 402) {
+ super(message);
+ this.status = status;
+ this.code = code;
+ this.name = 'BillingError';
+
+ // Fix prototype chain for proper instanceof behavior with custom Error classes
+ Object.setPrototypeOf(this, new.target.prototype);
+ }
+}
diff --git a/packages/runtime/src/modules/agent-runner/services/agent-request-handler.ts b/packages/runtime/src/modules/agent-runner/services/agent-request-handler.ts
new file mode 100644
index 00000000..962914c6
--- /dev/null
+++ b/packages/runtime/src/modules/agent-runner/services/agent-request-handler.ts
@@ -0,0 +1,75 @@
+import { Request } from "express";
+
+import { AgentProcess, Logger } from "@smythos/sre";
+
+const console = Logger("(Agent Runner) Service: Agent Request Handler");
+
+export async function processAgentRequest(agent: any, req: Request) {
+ if (!agent) {
+ return { status: 404, data: "Agent not found" };
+ }
+ //const req = agent.agentRequest;
+
+ req.socket.on("close", () => {
+ // console.log('Client socket closed, killing agent');
+ // Handle the cancellation logic
+ // agent.kill();
+ });
+
+ const hasDebugHeader = [
+ "X-DEBUG-RUN",
+ "X-DEBUG-READ",
+ "X-DEBUG-INJ",
+ "X-DEBUG-STOP",
+ ].some((header) => req.header(header));
+
+ if (hasDebugHeader) {
+ return { status: 403, data: "Debug functions are not supported" };
+ }
+
+ return runAgentProcess(agent, req);
+}
+
+async function runAgentProcess(agent: any, req: any) {
+ try {
+ //extract endpoint path
+ //live agents (dev) do not have a version number
+ //deployed agents have a version number
+ const pathMatches = req.path.match(/(^\/v[0-9]+\.[0-9]+?)?(\/api\/(.+)?)/);
+ if (!pathMatches || !pathMatches[2]) {
+ return { status: 404, data: { error: "Endpoint not found" } };
+ }
+
+ const { data: result } = await AgentProcess.load(req._agent)
+ .run({
+ ...req,
+ path: req.path,
+ url: undefined,
+ })
+ .catch((error) => ({ data: { error: error.toString() } }));
+
+ if (result.error) {
+ console.error("ERROR", result.error);
+ return {
+ status: 500,
+ data: {
+ ...result,
+ error: result.error.toString(),
+ agentId: agent?.id,
+ agentName: agent?.name,
+ },
+ };
+ }
+
+ return { status: 200, data: result };
+ } catch (error: any) {
+ console.error(error);
+ if (error.response) {
+ // The request was made, but the server responded with a non-2xx status
+ return { status: error.response.status, data: error.response.data };
+ } else {
+ // Some other error occurred
+ return { status: 500, data: "Internal Server Error" };
+ }
+ }
+}
diff --git a/packages/runtime/src/modules/agent-runner/services/logto-helper.ts b/packages/runtime/src/modules/agent-runner/services/logto-helper.ts
new file mode 100644
index 00000000..ccbf06e0
--- /dev/null
+++ b/packages/runtime/src/modules/agent-runner/services/logto-helper.ts
@@ -0,0 +1,69 @@
+import axios from 'axios';
+import qs from 'querystring';
+
+import config from '@agent-runner/config';
+//M2M test
+const postData = {
+ grant_type: 'client_credentials',
+ resource: 'https://default.logto.app/api',
+ scope: 'all',
+};
+
+const base64Credentials = Buffer.from(`${config.env.LOGTO_M2M_APP_ID}:${config.env.LOGTO_M2M_APP_SECRET}`, 'utf8').toString('base64');
+
+let tokenData = {
+ access_token: null,
+};
+export function getM2MToken(resource?, scope?) {
+ return new Promise((resolve, reject) => {
+ if (tokenData.access_token) {
+ return resolve(tokenData.access_token);
+ }
+
+ const body = {
+ grant_type: 'client_credentials',
+ resource: resource || config.env.LOGTO_API_RESOURCE,
+ scope: scope || '',
+ };
+ axios({
+ method: 'post',
+ url: `${config.env.LOGTO_SERVER}/oidc/token`,
+ headers: {
+ Authorization: 'Basic ' + base64Credentials,
+ 'Content-Type': 'application/x-www-form-urlencoded',
+ },
+ data: qs.stringify(body),
+ })
+ .then((response) => {
+ tokenData.access_token = response.data.access_token;
+ setTimeout(
+ () => {
+ tokenData.access_token = null;
+ },
+ (response.data.expires_in - 100) * 1000,
+ );
+ resolve(tokenData.access_token);
+ })
+ .catch((error) => {
+ reject({ error: error.response.data });
+ });
+ });
+}
+
+export async function getUserInfo(userId: string) {
+ const token = await getM2MToken('https://default.logto.app/api', 'all');
+
+ const response: any = await axios({
+ method: 'get',
+ url: `${config.env.LOGTO_SERVER}/api/users/${userId}`,
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ }).catch((error) => ({ error }));
+
+ if (response.error) {
+ return null;
+ }
+
+ return response.data;
+}
diff --git a/packages/runtime/src/modules/agent-runner/services/smythAPIReq.ts b/packages/runtime/src/modules/agent-runner/services/smythAPIReq.ts
new file mode 100644
index 00000000..9e185c18
--- /dev/null
+++ b/packages/runtime/src/modules/agent-runner/services/smythAPIReq.ts
@@ -0,0 +1,15 @@
+import axios from 'axios';
+
+import config from '@agent-runner/config';
+
+//middleware sys API
+export const mwSysAPI = axios.create({
+ baseURL: `${config.env.SMYTH_API_BASE_URL}/_sysapi/v1`,
+});
+export function includeAuth(token: string) {
+ return {
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ };
+}
diff --git a/packages/runtime/src/modules/agent-runner/types/agent.types.ts b/packages/runtime/src/modules/agent-runner/types/agent.types.ts
new file mode 100644
index 00000000..b24fd833
--- /dev/null
+++ b/packages/runtime/src/modules/agent-runner/types/agent.types.ts
@@ -0,0 +1,57 @@
+// **********************************************************************************
+//* Until now, the agent.types.ts file is identical across sre-builder-debugger, sre-agent-server, and sre-embodiment-server.
+//* Any changes made here should also be applied to the corresponding files in all three services.
+// **********************************************************************************
+
+export type PLAN_NAMES =
+ | 'v4_Enterprise_T1'
+ | 'v4_Enterprise_T2'
+ | 'v4_Enterprise_T3'
+ | 'v4_Enterprise_T4'
+ | 'v4_Scaleup'
+ | 'v4_Builder'
+ | 'v4_Startup'
+ | 'SmythOS Free'
+ | 'Early Adopters'
+ | 'Premium'
+ | 'Enterprise'; // v3 enterprise
+
+export type PlanInfo = {
+ planName: PLAN_NAMES;
+ isDefaultPlan?: boolean;
+ flags: {
+ hasBuiltinModels: boolean;
+ };
+ properties: {
+ freeCredits: number;
+ };
+};
+
+export type ComponentConfig = {
+ id: string;
+ name: string;
+ title?: string;
+ displayName?: string;
+ eventId?: string;
+ data?: {
+ model?: string;
+ [key: string]: any;
+ };
+};
+
+export type Agent = {
+ agentRequest: {
+ req: {
+ _agent: {
+ planInfo: PlanInfo;
+ parentTeamId: string;
+ teamId: string;
+ };
+ };
+ };
+};
+
+// **********************************************************************************
+//* Until now, the agent.types.ts file is identical across sre-builder-debugger, sre-agent-server, and sre-embodiment-server.
+//* Any changes made here should also be applied to the corresponding files in all three services.
+// **********************************************************************************
diff --git a/packages/runtime/src/modules/debugger/routes/agent/routes.ts b/packages/runtime/src/modules/debugger/routes/agent/routes.ts
index 476f17d4..f132c734 100644
--- a/packages/runtime/src/modules/debugger/routes/agent/routes.ts
+++ b/packages/runtime/src/modules/debugger/routes/agent/routes.ts
@@ -1,7 +1,4 @@
-import express from "express";
-
-import { Logger } from "@smythos/sre";
-
+import { createDebuggerRouter } from "@core/shared-agent-router";
import agentLoader from "@debugger/middlewares/agentLoader.mw";
import {
createSseConnection,
@@ -9,69 +6,9 @@ import {
processAgentRequest,
} from "@debugger/services/agent-request-handler";
-const console = Logger("[Debugger] Router: Agent");
-
-const router = express.Router();
-
-const middlewares = [agentLoader];
-
-router.get("/agent/:id/debugSession", (req, res, next) => {
- console.log(
- `Getting debug session for agent ${req.params.id} with client IP ${req.headers["x-forwarded-for"]} - ${req.socket.remoteAddress}. x-hash-id ${req.headers["x-hash-id"]}`
- );
- const dbgSession = getDebugSession(req.params.id);
- res.send({ dbgSession });
-});
-
-router.get("/agent/:id/monitor", (req, res, next) => {
- const sseId = createSseConnection(req);
-
- // Set headers for SSE
- res.setHeader("Content-Type", "text/event-stream");
- res.setHeader("Cache-Control", "no-cache");
- res.setHeader("Connection", "keep-alive");
-
- // Send the unique ID as the first event
- res.write(`event: init\n`);
- res.write(`data: ${sseId}\n\n`);
-});
-
-router.post(`/api/*`, middlewares, async (req, res) => {
- const agent = req._agent;
- const result: any = await processAgentRequest(agent.id, req);
-
- return res.status(result?.status || 500).send(result?.data);
-});
-router.get(`/api/*`, middlewares, async (req, res) => {
- const agent: any = req._agent;
- const result: any = await processAgentRequest(agent.id, req);
-
- return res.status(result?.status || 500).send(result?.data);
-});
-
-router.post(`/:version/api/*`, middlewares, async (req, res) => {
- const agent: any = req._agent;
- const result: any = await processAgentRequest(agent.id, req);
- return res.status(result?.status || 500).send(result?.data);
-});
-router.get(`/:version/api/*`, middlewares, async (req, res) => {
- const agent: any = req._agent;
- const result: any = await processAgentRequest(agent.id, req);
- return res.status(result?.status || 500).send(result?.data);
+const router = createDebuggerRouter(agentLoader, processAgentRequest, {
+ getDebugSession,
+ createSseConnection,
});
-router.post(
- /^\/v[0-9]+(\.[0-9]+)?\/api\/(.+)/,
- middlewares,
- async (req, res) => {
- const agent: any = req._agent;
- if (!agent) {
- res.status(404).json({ error: "Agent not found" });
- return;
- }
- const result: any = await processAgentRequest(agent.id, req);
- return res.status(result?.status || 500).send(result?.data);
- }
-);
-
export default router;