Bundle: redb-route / redb.Route.Exec (redb.Route.Exec.txt), 9 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.Exec/ExecComponent.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Exec/ExecComponent.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.Exec;
///
/// Process-execution component. Scheme: exec .
///
/// Producer: synchronous request/response — runs the configured command and writes
/// the result (stdout/stderr/exit code) to .
///
///
/// Consumer: scheduled poller driven by — fires the command on
/// a fixed interval and pushes the result into the route pipeline.
///
///
/// URI: exec://run?command=git&args=status&timeoutMs=5000&allowedCommands=git,ls
///
///
public sealed class ExecComponent : ComponentBase
{
///
public override string Scheme => "exec";
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new ExecEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.Validate();
return new ExecEndpoint(uri, this, options);
}
}
///
/// Exec endpoint. Creates either a request/response producer or a scheduled consumer.
/// The host part of the URI (exec://run ) is informational and not interpreted —
/// the actual command target comes from or
/// the inbound exchange.
///
public sealed class ExecEndpoint : EndpointBase
{
/// Creates an exec endpoint.
public ExecEndpoint(EndpointUri uri, ExecComponent component, ExecEndpointOptions options)
: base(uri, component, options)
{
}
/// Endpoint options for external access.
internal ExecEndpointOptions EndpointOptions => Options;
///
public override IProducer CreateProducer() => new ExecProducer(this, Options);
///
public override IConsumer CreateConsumer(IProcessor processor)
{
ArgumentNullException.ThrowIfNull(processor);
return new ExecConsumer(this, Options, processor);
}
}
Path: redb-route/redb.Route.Exec/ExecConsumer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Exec/ExecConsumer.cs
----
using System.Diagnostics;
using System.Text.RegularExpressions;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Exec;
///
/// Scheduled exec consumer. Fires the configured command on a fixed interval (via
/// ) and pushes the resulting exchange into the route pipeline.
///
/// Supported schedule formats: 500ms , 30s , 5m , 1h .
/// Cron expressions are intentionally not handled here — chain
/// From("quartz://<cron>").To("exec://run?command=...") when cron is required.
///
///
public sealed class ExecConsumer : IConsumer
{
private static readonly Regex IntervalPattern =
new(@"^\s*(\d+)\s*(ms|s|m|h)\s*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
private readonly ExecEndpoint _endpoint;
private readonly ExecEndpointOptions _options;
private readonly IProcessor _processor;
private CancellationTokenSource? _cts;
private Task? _loop;
private ExecProducer? _producer;
/// Creates a scheduled exec consumer.
public ExecConsumer(ExecEndpoint endpoint, ExecEndpointOptions options, IProcessor processor)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
_processor = processor ?? throw new ArgumentNullException(nameof(processor));
}
///
public IEndpoint? Endpoint => _endpoint;
///
public Task Start(CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(_options.Schedule))
throw new InvalidOperationException(
"Consumer mode for 'exec://' requires '?schedule=' (e.g. '30s', '5m', '1h'). " +
"For cron expressions chain From(\"quartz://...\").To(\"exec://run?command=...\").");
if (string.IsNullOrWhiteSpace(_options.Command))
throw new InvalidOperationException(
"Consumer mode for 'exec://' requires the URI 'command=' option to be set.");
var interval = ParseInterval(_options.Schedule)
?? throw new InvalidOperationException(
$"Schedule '{_options.Schedule}' is not a valid interval. " +
"Accepted formats: '500ms', '30s', '5m', '1h'.");
_producer = new ExecProducer(_endpoint, _options);
_cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
_loop = RunLoopAsync(interval, _cts.Token);
return _producer.Start(ct);
}
///
public async Task Stop(CancellationToken ct = default)
{
if (_cts is null) return;
try { await _cts.CancelAsync().ConfigureAwait(false); } catch { /* idempotent */ }
if (_loop is { } loop)
{
try { await loop.ConfigureAwait(false); }
catch (OperationCanceledException) { /* expected */ }
}
if (_producer is not null)
{
try { await _producer.Stop(ct).ConfigureAwait(false); } catch { /* best-effort */ }
_producer = null;
}
_cts.Dispose();
_cts = null;
_loop = null;
}
private async Task RunLoopAsync(TimeSpan interval, CancellationToken ct)
{
using var timer = new PeriodicTimer(interval);
while (!ct.IsCancellationRequested)
{
try
{
if (!await timer.WaitForNextTickAsync(ct).ConfigureAwait(false))
return;
}
catch (OperationCanceledException) { return; }
try
{
await FireOnceAsync(ct).ConfigureAwait(false);
}
catch (OperationCanceledException) { return; }
catch (Exception ex)
{
// The tick's own span carries the failure. Continue — one failed tick must not kill the consumer.
_endpoint.RecordError(ex);
}
}
}
private async Task FireOnceAsync(CancellationToken ct)
{
var ctx = (_endpoint.Component as ComponentBase)?.Context;
var scopeFactory = ctx?.GetServiceProvider()
?.GetService(typeof(Microsoft.Extensions.DependencyInjection.IServiceScopeFactory))
as Microsoft.Extensions.DependencyInjection.IServiceScopeFactory;
var exchange = Exchange.Create(new Message(string.Empty), scopeFactory);
// A tick carries no trace context: its span is a root, never a child of the activity the timer loop holds. The
// run of the command (the producer's client span) and the route sit under it.
using var span = RouteTelemetryExtensions.StartConsumerSpan(
ctx, $"exec {Path.GetFileName(_options.Command ?? string.Empty)} receive", ActivityKind.Consumer,
"process.executable.name", Path.GetFileName(_options.Command ?? string.Empty), _endpoint.Uri.NormalizedKey,
null, static (_, _) => null, operation: "receive");
// The scheduler owns this exchange for the whole tick: dispose it in finally so its
// per-exchange DI scope (and any redb connection resolved downstream) is released every
// tick — otherwise each scheduled fire would leak a scope and drain the connection pool.
try
{
if (!string.IsNullOrWhiteSpace(_options.Command))
exchange.In.Headers[ExecHeaders.Command] = _options.Command;
if (!string.IsNullOrWhiteSpace(_options.Args))
exchange.In.Headers[ExecHeaders.Args] = _options.Args;
await _producer!.Process(exchange, ct).ConfigureAwait(false);
await _processor.Process(exchange, ct).ConfigureAwait(false);
if (exchange.Exception is { } failure && !exchange.ExceptionHandled
&& (failure is not OperationCanceledException || !ct.IsCancellationRequested))
span.Activity.RecordFailure(failure);
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
// Our own stop is not a failure of the tick; any other cancellation is.
span.Activity.RecordFailure(ex);
throw;
}
finally
{
await exchange.DisposeAsync().ConfigureAwait(false);
}
}
internal static TimeSpan? ParseInterval(string schedule)
{
var m = IntervalPattern.Match(schedule);
if (!m.Success) return null;
if (!long.TryParse(m.Groups[1].Value, out var n) || n <= 0) return null;
return m.Groups[2].Value.ToLowerInvariant() switch
{
"ms" => TimeSpan.FromMilliseconds(n),
"s" => TimeSpan.FromSeconds(n),
"m" => TimeSpan.FromMinutes(n),
"h" => TimeSpan.FromHours(n),
_ => null
};
}
}
Path: redb-route/redb.Route.Exec/ExecEndpointOptions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Exec/ExecEndpointOptions.cs
----
using redb.Route.Core;
namespace redb.Route.Exec;
///
/// Options for the exec endpoint. Shared by producer and consumer.
///
/// URI: exec://run?command=git&args=status&timeoutMs=5000&allowedCommands=git,ls,pwd
///
///
public sealed class ExecEndpointOptions : EndpointOptions
{
// ── Command target ──────────────────────────────────────────────
///
/// The command to execute. May be overridden per-call by the
/// header or by a JSON body's command field.
///
public string? Command { get; set; }
///
/// Default argument list, whitespace-separated. May be overridden per-call by the
/// header or by a JSON body's args array.
///
public string? Args { get; set; }
// ── Allowlist ───────────────────────────────────────────────────
///
/// Comma-separated list of permitted command names. When non-empty, every request must
/// resolve to one of these commands (matched against the executable file name without
/// extension). When empty, all commands are allowed — the framework defers to the host
/// OS for permissions. For LLM-tool exposure, set this explicitly.
///
public string? AllowedCommands { get; set; }
// ── Process environment ─────────────────────────────────────────
/// Working directory for the spawned process (default: the current process cwd).
public string? WorkingDirectory { get; set; }
///
/// Comma-separated KEY=VALUE environment overrides. These are added on top of
/// the host process environment and override any keys with the same name.
///
public string? EnvironmentOverrides { get; set; }
///
/// When true , the spawned process inherits no environment variables — only the
/// overrides supplied via are passed in. Default false .
///
public bool ScrubEnvironment { get; set; }
// ── Limits ──────────────────────────────────────────────────────
///
/// Wall-clock timeout in milliseconds. The process is forcibly terminated when exceeded
/// and the output exchange is flagged via . Default 30000.
/// 0 = no timeout.
///
public int TimeoutMs { get; set; } = 30_000;
/// Maximum bytes captured from stdout. Excess output is silently dropped. Default 1 MiB.
public int MaxStdoutBytes { get; set; } = 1024 * 1024;
/// Maximum bytes captured from stderr. Excess output is silently dropped. Default 256 KiB.
public int MaxStderrBytes { get; set; } = 256 * 1024;
///
/// When true , stderr is folded into the JSON response body alongside stdout.
/// When false , only stdout is set as the body and stderr is exposed via headers
/// ( ) only. Default true .
///
public bool CaptureStderrInBody { get; set; } = true;
// ── Output shape ────────────────────────────────────────────────
///
/// When true (default), is set to a
/// JSON object string of the form {"stdout":"...","stderr":"...","exitCode":0} — the
/// shape required by the LLM tool ABI. When false , only stdout is written as a plain
/// string body and metadata is exposed exclusively through headers.
///
public bool JsonResponse { get; set; } = true;
// ── Consumer (scheduled) ────────────────────────────────────────
///
/// Schedule expression for consumer mode. Supported formats: 500ms , 30s , 5m , 1h .
/// Cron expressions are not supported by the inline consumer — use From("quartz://...") for cron.
///
public string? Schedule { get; set; }
///
public override void Validate()
{
if (TimeoutMs < 0)
throw new ArgumentException("TimeoutMs must be >= 0 (0 = unlimited).", nameof(TimeoutMs));
if (MaxStdoutBytes <= 0)
throw new ArgumentException("MaxStdoutBytes must be > 0.", nameof(MaxStdoutBytes));
if (MaxStderrBytes <= 0)
throw new ArgumentException("MaxStderrBytes must be > 0.", nameof(MaxStderrBytes));
}
}
Path: redb-route/redb.Route.Exec/ExecHeaders.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Exec/ExecHeaders.cs
----
namespace redb.Route.Exec;
///
/// Well-known header keys for exec exchanges.
///
public static class ExecHeaders
{
/// Common prefix for all exec component headers.
public const string Prefix = "redbExec.";
/// Inbound: command name to execute (overrides URI command when set).
public const string Command = "redbExec.Command";
/// Inbound: argument list (string[] or string parsed by simple whitespace split).
public const string Args = "redbExec.Args";
/// Outbound: process exit code (int).
public const string ExitCode = "redbExec.ExitCode";
/// Outbound: standard output (string).
public const string Stdout = "redbExec.Stdout";
/// Outbound: standard error (string).
public const string Stderr = "redbExec.Stderr";
/// Outbound: number of stdout bytes captured (long).
public const string StdoutBytes = "redbExec.StdoutBytes";
/// Outbound: number of stderr bytes captured (long).
public const string StderrBytes = "redbExec.StderrBytes";
/// Outbound: wall-clock duration of the process in milliseconds (long).
public const string DurationMs = "redbExec.DurationMs";
/// Outbound: true when the process was killed by the timeout watchdog.
public const string TimedOut = "redbExec.TimedOut";
/// Outbound: command line string actually launched (for audit/debugging).
public const string CommandLine = "redbExec.CommandLine";
}
Path: redb-route/redb.Route.Exec/ExecProducer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Exec/ExecProducer.cs
----
using System.Diagnostics;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.Exec;
///
/// Spawns OS processes synchronously and returns stdout/stderr/exitCode on the outbound exchange.
///
/// Input resolution order (highest → lowest priority):
///
/// - JSON body of the form
{"command":"...","args":["..."]} on .
/// / headers.
/// / URI options.
///
///
///
/// Security: when is set, the resolved
/// command must match one of the listed names (case-insensitive, file-name-only). Requests
/// against commands not on the allowlist throw .
///
///
public sealed class ExecProducer : ConnectableProducer
{
private readonly ExecEndpoint _endpoint;
private readonly ExecEndpointOptions _options;
private readonly HashSet? _allowed;
private readonly Dictionary? _envOverrides;
///
protected override IEndpoint ProducerEndpoint => _endpoint;
///
protected override string ProducerName => $"exec:{_options.Command ?? ""}";
/// Creates an exec producer.
public ExecProducer(ExecEndpoint endpoint, ExecEndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
_allowed = ParseAllowed(options.AllowedCommands);
_envOverrides = ParseEnv(options.EnvironmentOverrides);
}
///
protected override Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
EnsureStarted();
ArgumentNullException.ThrowIfNull(exchange);
var (command, args) = ResolveCommand(exchange);
if (string.IsNullOrWhiteSpace(command))
throw new InvalidOperationException(
"exec://: no command resolved. Set the URI 'command' option, the redbExec.Command header, " +
"or send a JSON body with a \"command\" field.");
// The span is named after the resolved executable, the file name only: the arguments, which carry secrets,
// never reach it.
var executable = Path.GetFileName(command);
using var activity = RouteTelemetryExtensions.StartTransportSpan(
(_endpoint.Component as ComponentBase)?.Context,
$"exec {executable}", ActivityKind.Client,
"process.executable.name", executable,
_endpoint.Uri.NormalizedKey);
try
{
EnsureAllowed(command);
var psi = BuildStartInfo(command, args);
// Do NOT log argument values — they routinely carry secrets (tokens, passwords
// passed as CLI flags). Emit the executable and the argument count only.
Logger?.LogDebug("exec → {Command} ({ArgCount} args)", psi.FileName, args.Count);
var result = await RunAsync(psi, ct).ConfigureAwait(false);
if (activity is { IsAllDataRequested: true })
activity.SetTag("process.exit.code", result.ExitCode);
WriteOutput(exchange, command, args, result);
}
catch (Exception ex) when (ex is not OperationCanceledException || !ct.IsCancellationRequested)
{
// Only our own token cancelling the run is a stop; a refused command or a failed start marks the span.
activity.RecordFailure(ex);
throw;
}
}
// ── Resolution ─────────────────────────────────────────────────
internal (string Command, IReadOnlyList Args) ResolveCommand(IExchange exchange)
{
// 1) JSON body
var body = exchange.In.Body;
if (body is string s && !string.IsNullOrWhiteSpace(s) && LooksLikeJson(s))
{
if (TryParseJson(s, out var jc, out var ja))
return (jc!, ja);
}
// 2) Headers
if (exchange.In.Headers.TryGetValue(ExecHeaders.Command, out var hc) && hc is string hcs && !string.IsNullOrWhiteSpace(hcs))
{
var ha = exchange.In.Headers.TryGetValue(ExecHeaders.Args, out var rawArgs) ? rawArgs : null;
return (hcs, NormalizeArgs(ha));
}
// 3) Options
return (_options.Command ?? string.Empty, SplitArgs(_options.Args));
}
private static bool LooksLikeJson(string s)
{
var t = s.AsSpan().TrimStart();
return t.Length > 0 && t[0] == '{';
}
private static bool TryParseJson(string json, out string? command, out IReadOnlyList args)
{
command = null;
args = Array.Empty();
try
{
using var doc = JsonDocument.Parse(json);
var root = doc.RootElement;
if (root.ValueKind != JsonValueKind.Object) return false;
if (root.TryGetProperty("command", out var c) && c.ValueKind == JsonValueKind.String)
command = c.GetString();
if (root.TryGetProperty("args", out var a))
{
if (a.ValueKind == JsonValueKind.Array)
{
var list = new List(a.GetArrayLength());
foreach (var el in a.EnumerateArray())
list.Add(el.ValueKind == JsonValueKind.String ? el.GetString()! : el.ToString());
args = list;
}
else if (a.ValueKind == JsonValueKind.String)
{
args = SplitArgs(a.GetString());
}
}
return command is not null;
}
catch (JsonException)
{
return false;
}
}
private static IReadOnlyList NormalizeArgs(object? raw) => raw switch
{
null => Array.Empty(),
string s => SplitArgs(s),
IEnumerable e => e.ToArray(),
_ => SplitArgs(raw.ToString())
};
private static IReadOnlyList SplitArgs(string? s)
{
if (string.IsNullOrWhiteSpace(s)) return Array.Empty();
// Whitespace split that respects double-quoted spans.
var list = new List();
var sb = new StringBuilder();
var inQuote = false;
foreach (var ch in s)
{
if (ch == '"') { inQuote = !inQuote; continue; }
if (!inQuote && char.IsWhiteSpace(ch))
{
if (sb.Length > 0) { list.Add(sb.ToString()); sb.Clear(); }
continue;
}
sb.Append(ch);
}
if (sb.Length > 0) list.Add(sb.ToString());
return list;
}
// ── Allowlist ──────────────────────────────────────────────────
internal void EnsureAllowed(string command)
{
if (_allowed is null || _allowed.Count == 0) return;
var name = ExtractCommandName(command);
if (!_allowed.Contains(name))
throw new UnauthorizedAccessException(
$"exec://: command '{name}' is not on the allowlist. " +
$"Allowed: {string.Join(", ", _allowed)}.");
}
private static string ExtractCommandName(string command)
{
var path = command.Trim().Trim('"');
var name = Path.GetFileNameWithoutExtension(path);
if (string.IsNullOrEmpty(name)) name = path;
return name.ToLowerInvariant();
}
private static HashSet? ParseAllowed(string? csv)
{
if (string.IsNullOrWhiteSpace(csv)) return null;
var set = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (var part in csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
set.Add(part.ToLowerInvariant());
return set.Count == 0 ? null : set;
}
private static Dictionary? ParseEnv(string? csv)
{
if (string.IsNullOrWhiteSpace(csv)) return null;
var dict = new Dictionary(StringComparer.Ordinal);
foreach (var part in csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var eq = part.IndexOf('=');
if (eq <= 0) continue;
var k = part[..eq].Trim();
var v = part[(eq + 1)..].Trim();
dict[k] = v;
}
return dict.Count == 0 ? null : dict;
}
// ── Process spawn ──────────────────────────────────────────────
private ProcessStartInfo BuildStartInfo(string command, IReadOnlyList args)
{
var psi = new ProcessStartInfo
{
FileName = command,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = false,
WorkingDirectory = _options.WorkingDirectory ?? string.Empty,
// Decode child output using the host console's active codepage. Without this, .NET
// defaults to UTF-8 while cmd.exe / wmic / net / fsutil emit OEM bytes (cp866 on RU,
// cp437 on EN, cp932 on JP, …) — the mismatch shows up as U+FFFD replacement chars.
StandardOutputEncoding = ConsoleOutputEncoding,
StandardErrorEncoding = ConsoleOutputEncoding,
};
foreach (var a in args)
psi.ArgumentList.Add(a);
if (_options.ScrubEnvironment)
psi.Environment.Clear();
if (_envOverrides is not null)
{
foreach (var (k, v) in _envOverrides)
psi.Environment[k] = v;
}
return psi;
}
///
/// Encoding used to decode the child process's stdout/stderr. On Windows this is the
/// active console codepage (OEM); elsewhere UTF-8. Computed once per process.
///
private static readonly Encoding ConsoleOutputEncoding = ResolveConsoleOutputEncoding();
private static Encoding ResolveConsoleOutputEncoding()
{
if (!OperatingSystem.IsWindows())
return Encoding.UTF8;
// CodePagesEncodingProvider gives us cp866/cp1251/etc. on .NET (which only ships
// ASCII/UTF-8/UTF-16/UTF-32 in the BCL).
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
try { return Encoding.GetEncoding(GetOEMCP()); }
catch { return Console.OutputEncoding; }
}
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern int GetOEMCP();
private async Task RunAsync(ProcessStartInfo psi, CancellationToken ct)
{
using var process = new Process { StartInfo = psi, EnableRaisingEvents = true };
var stdoutCap = new BoundedBuffer(_options.MaxStdoutBytes);
var stderrCap = new BoundedBuffer(_options.MaxStderrBytes);
process.OutputDataReceived += (_, e) => { if (e.Data is not null) stdoutCap.AppendLine(e.Data); };
process.ErrorDataReceived += (_, e) => { if (e.Data is not null) stderrCap.AppendLine(e.Data); };
var sw = Stopwatch.StartNew();
if (!process.Start())
throw new InvalidOperationException($"Failed to start process '{psi.FileName}'.");
process.BeginOutputReadLine();
process.BeginErrorReadLine();
var timedOut = false;
try
{
using var timeoutCts = _options.TimeoutMs > 0
? CancellationTokenSource.CreateLinkedTokenSource(ct)
: CancellationTokenSource.CreateLinkedTokenSource(ct);
if (_options.TimeoutMs > 0)
timeoutCts.CancelAfter(_options.TimeoutMs);
try
{
await process.WaitForExitAsync(timeoutCts.Token).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
timedOut = !ct.IsCancellationRequested;
TryKill(process);
if (ct.IsCancellationRequested) throw;
}
}
finally
{
sw.Stop();
}
// Drain any pending async-stream data.
process.WaitForExit();
return new ExecResult(
ExitCode: timedOut ? -1 : process.ExitCode,
Stdout: stdoutCap.ToString(),
Stderr: stderrCap.ToString(),
StdoutBytes: stdoutCap.WrittenBytes,
StderrBytes: stderrCap.WrittenBytes,
DurationMs: sw.ElapsedMilliseconds,
TimedOut: timedOut);
}
private static void TryKill(Process p)
{
try { if (!p.HasExited) p.Kill(entireProcessTree: true); }
catch { /* best-effort */ }
}
// ── Output ─────────────────────────────────────────────────────
private void WriteOutput(IExchange exchange, string command, IReadOnlyList args, ExecResult r)
{
exchange.Out ??= exchange.In.Clone();
var commandLine = command + (args.Count > 0 ? " " + string.Join(' ', args) : string.Empty);
if (_options.JsonResponse)
{
// JSON body — the shape an LLM tool will deserialise.
var payload = _options.CaptureStderrInBody
? new { stdout = r.Stdout, stderr = r.Stderr, exitCode = r.ExitCode, timedOut = r.TimedOut }
: (object)new { stdout = r.Stdout, exitCode = r.ExitCode, timedOut = r.TimedOut };
exchange.Out.Body = JsonSerializer.Serialize(payload);
exchange.Out.ContentType = "application/json";
}
else
{
exchange.Out.Body = _options.CaptureStderrInBody && r.Stderr.Length > 0
? r.Stdout + r.Stderr
: r.Stdout;
exchange.Out.ContentType = "text/plain";
}
exchange.Out.Headers[ExecHeaders.ExitCode] = r.ExitCode;
exchange.Out.Headers[ExecHeaders.Stdout] = r.Stdout;
exchange.Out.Headers[ExecHeaders.Stderr] = r.Stderr;
exchange.Out.Headers[ExecHeaders.StdoutBytes] = r.StdoutBytes;
exchange.Out.Headers[ExecHeaders.StderrBytes] = r.StderrBytes;
exchange.Out.Headers[ExecHeaders.DurationMs] = r.DurationMs;
exchange.Out.Headers[ExecHeaders.TimedOut] = r.TimedOut;
exchange.Out.Headers[ExecHeaders.CommandLine] = commandLine;
}
private readonly record struct ExecResult(
int ExitCode,
string Stdout,
string Stderr,
long StdoutBytes,
long StderrBytes,
long DurationMs,
bool TimedOut);
///
/// A capped string buffer that drops anything past the configured byte budget. Ensures
/// a runaway process cannot exhaust the host process memory.
///
private sealed class BoundedBuffer
{
private readonly int _max;
private readonly StringBuilder _sb = new();
private long _written;
public BoundedBuffer(int max) => _max = max;
public long WrittenBytes => _written;
public void AppendLine(string line)
{
// Approximate: count UTF-8 bytes for the cap (worst case 4 bytes/char).
// We use char count + line ending here as a proxy — fast and good enough.
var add = line.Length + Environment.NewLine.Length;
_written += add;
if (_sb.Length >= _max) return;
var room = _max - _sb.Length;
if (line.Length + 1 <= room)
{
_sb.AppendLine(line);
}
else if (room > 0)
{
_sb.Append(line.AsSpan(0, Math.Min(line.Length, room)));
}
}
public override string ToString() => _sb.ToString();
}
}
Path: redb-route/redb.Route.Exec/Extensions/ServiceCollectionExtensions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Exec/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
namespace redb.Route.Exec;
///
/// Extension methods for registering the exec component with dependency injection.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the exec component with the route context.
///
public static IServiceCollection AddRedbRouteExec(this IServiceCollection services)
{
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteComponent();
return services;
}
}
Path: redb-route/redb.Route.Exec/Fluent/ExecDsl.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Exec/Fluent/ExecDsl.cs
----
using System.Text;
namespace redb.Route.Exec;
///
/// Fluent entry point for exec endpoints. Build URIs without manual string concatenation.
///
/// // Producer — request/response
/// .To(ExecDsl.Run("git").Args("status").AllowedCommands("git").TimeoutMs(5000))
///
/// // Consumer — scheduled
/// .From(ExecDsl.Run("./health-check.sh").Schedule("5m"))
///
///
public static class ExecDsl
{
/// Build an exec endpoint URI for the given command. The host part is fixed at run .
public static ExecBuilder Run(string? command = null) => new(command);
}
/// Fluent builder for exec endpoint URIs. Scheme: exec .
public sealed class ExecBuilder
{
private string? _command;
private string? _args;
private string? _allowedCommands;
private string? _workingDirectory;
private string? _envOverrides;
private bool _scrubEnv;
private int? _timeoutMs;
private int? _maxStdoutBytes;
private int? _maxStderrBytes;
private bool? _captureStderrInBody;
private bool? _jsonResponse;
private string? _schedule;
internal ExecBuilder(string? command) => _command = command;
// ── Command target ─────────────────────────────────────────────
/// The command to execute (overrides the constructor argument).
public ExecBuilder Command(string command) { _command = command; return this; }
/// Default argument list (whitespace-separated; quotes preserved).
public ExecBuilder Args(params string[] args)
{
_args = args.Length == 0 ? null : string.Join(' ', args.Select(QuoteIfNeeded));
return this;
}
// ── Allowlist ──────────────────────────────────────────────────
/// Restrict execution to the given command names (file-name-only, case-insensitive).
public ExecBuilder AllowedCommands(params string[] commands)
{
_allowedCommands = commands.Length == 0 ? null : string.Join(',', commands);
return this;
}
// ── Process environment ────────────────────────────────────────
/// Working directory for the spawned process.
public ExecBuilder WorkingDirectory(string path) { _workingDirectory = path; return this; }
/// Add or override an environment variable.
public ExecBuilder EnvOverride(string key, string value)
{
var entry = $"{key}={value}";
_envOverrides = string.IsNullOrEmpty(_envOverrides) ? entry : _envOverrides + "," + entry;
return this;
}
/// When set, the spawned process inherits no host environment variables.
public ExecBuilder ScrubEnvironment(bool value = true) { _scrubEnv = value; return this; }
// ── Limits ─────────────────────────────────────────────────────
/// Wall-clock timeout in milliseconds (0 = unlimited).
public ExecBuilder TimeoutMs(int ms) { _timeoutMs = ms; return this; }
/// Cap stdout capture (bytes).
public ExecBuilder MaxStdoutBytes(int bytes) { _maxStdoutBytes = bytes; return this; }
/// Cap stderr capture (bytes).
public ExecBuilder MaxStderrBytes(int bytes) { _maxStderrBytes = bytes; return this; }
/// Whether to fold stderr into the body (default true).
public ExecBuilder CaptureStderrInBody(bool value = true) { _captureStderrInBody = value; return this; }
// ── Output shape ───────────────────────────────────────────────
/// Whether the outbound body is a JSON object (default true).
public ExecBuilder JsonResponse(bool value = true) { _jsonResponse = value; return this; }
// ── Scheduled consumer ─────────────────────────────────────────
/// Schedule the consumer to fire on a fixed interval (e.g. "30s" , "5m" ).
public ExecBuilder Schedule(string schedule) { _schedule = schedule; return this; }
// ── Build ──────────────────────────────────────────────────────
/// Build the URI string.
public string Build()
{
var sb = new StringBuilder("exec://run");
var sep = '?';
void Append(string key, string v)
{
sb.Append(sep);
sb.Append(key);
sb.Append('=');
sb.Append(Uri.EscapeDataString(v));
sep = '&';
}
void AppendStr(string key, string? v) { if (!string.IsNullOrEmpty(v)) Append(key, v); }
void AppendInt(string key, int? v) { if (v.HasValue) Append(key, v.Value.ToString()); }
void AppendBool(string key, bool v) { if (v) Append(key, "true"); }
void AppendBoolN(string key, bool? v) { if (v.HasValue) Append(key, v.Value.ToString().ToLowerInvariant()); }
AppendStr("command", _command);
AppendStr("args", _args);
AppendStr("allowedCommands", _allowedCommands);
AppendStr("workingDirectory", _workingDirectory);
AppendStr("environmentOverrides", _envOverrides);
AppendBool("scrubEnvironment", _scrubEnv);
AppendInt("timeoutMs", _timeoutMs);
AppendInt("maxStdoutBytes", _maxStdoutBytes);
AppendInt("maxStderrBytes", _maxStderrBytes);
AppendBoolN("captureStderrInBody", _captureStderrInBody);
AppendBoolN("jsonResponse", _jsonResponse);
AppendStr("schedule", _schedule);
return sb.ToString();
}
private static string QuoteIfNeeded(string a)
=> a.Any(char.IsWhiteSpace) ? "\"" + a + "\"" : a;
/// Implicit cast to string — use the builder anywhere a URI string is accepted.
public static implicit operator string(ExecBuilder b) => b.Build();
///
public override string ToString() => Build();
}
Path: redb-route/redb.Route.Exec/README.md
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Exec/README.md
----
# redb.Route.Exec
[](https://www.nuget.org/packages/redb.Route.Exec/)
Process-execution transport for the [redb.Route](https://github.com/redbase-app/redb) ESB framework.
Run shell commands as part of a route — synchronously (request/response) or on a fixed schedule —
with first-class allowlisting, working-directory and environment overrides, wall-clock timeouts,
and stdout/stderr byte caps.
> Scheme: `exec`
> URI: `exec://run?command=git&args=status&timeoutMs=5000&allowedCommands=git,ls,pwd`
## Why
The framework already speaks 22+ transports (HTTP, Kafka, SQL, …) but reaching out to the
operating system itself was a gap. `redb.Route.Exec` closes it. Two patterns dominate:
- **Tool execution from an LLM agent.** Wire the producer into `.AsLlmTool("shell")` and the
language model can issue commands through your route — with the same allowlist, timeout
and audit you put in front of every other tool.
- **Scheduled jobs.** Need a cron-less daily backup, health probe, or log rotation? The
consumer fires any command on a fixed interval and pipes the result into the next step
of your route (Slack, Kafka, S3, redb persistence, …).
## Install
```bash
dotnet add package redb.Route.Exec
```
## Quick start — request/response producer
```csharp
using redb.Route.Exec;
services.AddRedbRoute()
.AddRedbRouteExec();
routes.From(Direct.Endpoint("git-status"))
.To(ExecDsl.Run("git")
.Args("status", "--short")
.WorkingDirectory("/srv/app")
.AllowedCommands("git")
.TimeoutMs(5_000));
```
The exchange `Out.Body` is JSON shaped for the LLM tool ABI:
```json
{ "stdout": "M README.md\n", "stderr": "", "exitCode": 0, "timedOut": false }
```
Headers also expose `redbExec.ExitCode`, `redbExec.Stdout`, `redbExec.Stderr`,
`redbExec.DurationMs`, `redbExec.TimedOut`, `redbExec.CommandLine`.
## Quick start — scheduled consumer
```csharp
routes.From(ExecDsl.Run("./scripts/health-check.sh")
.Schedule("5m")
.TimeoutMs(30_000))
.Choice()
.When(e => e.In.Headers["redbExec.ExitCode"]?.ToString() != "0")
.To(slackAlerts)
.Otherwise()
.To(metricsLog);
```
`Schedule` accepts `500ms`, `30s`, `5m`, `1h`. For cron, chain `From("quartz://")`.
## Inputs (producer)
The producer resolves the command in this order:
1. **JSON body** — `{"command": "git", "args": ["status"]}`
2. **Headers** — `redbExec.Command` + `redbExec.Args`
3. **URI options** — `?command=git&args=status`
This is exactly the shape an LLM agent will produce when the producer is exposed as a
tool — no glue code required.
## Security
`AllowedCommands` is the primary control. When set, any request that resolves to a
command outside the list is rejected with `UnauthorizedAccessException`. Match is on the
file-name-only (case-insensitive), so `/usr/bin/git` and `git.exe` both match `git`.
Other controls:
- `WorkingDirectory` — pin the cwd; the spawned process cannot escape it on its own.
- `EnvironmentOverrides` — `KEY=VALUE,KEY2=VALUE2`. Overlaid on the host environment.
- `ScrubEnvironment` — start with an empty environment and apply only the overrides.
- `TimeoutMs` — wall-clock kill-switch. The whole process tree is terminated.
- `MaxStdoutBytes` / `MaxStderrBytes` — caps protect the host from runaway processes.
## Headers reference
| Header | Direction | Type | Notes |
| ----------------------- | --------- | ------ | ----------------------------------------------- |
| `redbExec.Command` | in | string | Overrides the URI option |
| `redbExec.Args` | in | string \| string[] | Whitespace-split or array |
| `redbExec.ExitCode` | out | int | `-1` when the process timed out |
| `redbExec.Stdout` | out | string | Capped at `MaxStdoutBytes` |
| `redbExec.Stderr` | out | string | Capped at `MaxStderrBytes` |
| `redbExec.StdoutBytes` | out | long | Total bytes captured (post-cap may be lower) |
| `redbExec.StderrBytes` | out | long | Total bytes captured (post-cap may be lower) |
| `redbExec.DurationMs` | out | long | Wall-clock execution time |
| `redbExec.TimedOut` | out | bool | `true` when the watchdog killed the process |
| `redbExec.CommandLine` | out | string | Exact command line launched |
## License
Apache-2.0
## Tracing
On the `redb.Route` activity source (`AddSource("redb.Route")`), with `redb.route.endpoint`:
- **Consumer (schedule).** One `Consumer` span per tick, `exec {executable} receive`. A tick carries no trace context,
so the span is a root, never a child of the activity the timer loop inherited from whoever started the routes; the
run of the command and the route are its children. A failed tick marks it an error; our own stop does not.
- **Producer.** One `Client` span per run, `exec {executable}`, with `process.executable.name` = the file name of the
resolved command and `process.exit.code`. The arguments, which often carry secrets, are never on the span. A refused
command, a failed start or a cancellation that is not our own marks it an error; a non-zero exit code does not, it is
in `redbExec.ExitCode`.
- `RouteEngineOptions.EnableTelemetry = false` opens neither span.
Path: redb-route/redb.Route.Exec/redb.Route.Exec.csproj
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Exec/redb.Route.Exec.csproj
----
redb.Route.Exec
Process execution transport for redb.Route ESB framework. Provides a request/response producer that runs OS commands and a scheduled consumer that fires commands on a fixed interval. Allowlist, working directory, environment overrides, timeout and stdout/stderr byte caps are all enforced by the endpoint.
esb;messaging;exec;process;shell;scheduled;llm;tools;redb
README.md