MODULE 03 · LESSON 3.7
Return script results, artifacts and failures
Follow structured values and files from a C# worker back through the plugin to the agent, then prepare deployment.
Lesson 17 of 88 · FabrCore 2.0
Overview
The script returns an ordinary C# value. The worker serializes it as JSON, the host deserializes it into ScriptExecutionResult, and the plugin returns that result through the normal AIFunction call. The model sees the result as tool output and can explain it or correct a failed script.
Keep values, output and errors separate
Input is a JsonElement and InputJson is its text form. A return statement supplies Value; Console.WriteLine supplies Output. Status identifies success, compiler errors, runtime exceptions, timeout, cancellation, memory/output limits or a worker failure. Check Status before using Value. Compiler diagnostics help the model correct code, but retrying a script with external side effects requires application judgment.
Use trusted database tools to authorize and query data, then pass bounded results to the script. Scripting is useful for transformations; it does not provide your data-access rules or prove the input set is complete.
Artifacts are bytes your application owns
Write files beneath OutputDirectory. The host collects at most 100 artifacts within the configured combined byte limit, returns names and bytes, then removes the execution directory. It does not create durable download links. Store the bytes in application storage before presenting them, and avoid placing large encoded files in model context.
A Blazor page can render validated Value data using known components or display a stored artifact link. This scripting feature does not compile Razor or load new component assemblies. Live services and circuit objects cannot cross into the worker.
Prepare once, execute in fresh workers
First initialization prepares the worker with the .NET 10 SDK. Prewarm explicitly before deployment on the target OS and architecture, preserve the cache and set AllowEnvironmentPreparation=false in production if workers must run without SDK or package-feed access. Production still needs the .NET 10 runtime. MSBuild does not discover Configure declarations automatically.
Defaults are 30 seconds including startup/compilation, a 512 MiB sampled worker working-set check, 32,768 console characters and 1 MiB of artifacts. JSON and errors are separately bounded; JSON uses a conservative UTF-8 byte bound. Memory monitoring is not a hard OS or child-process quota. A timeout attempts process-tree termination and does not roll back file or network effects.
Current safeguards and their limits
The current runtime provides supervised out-of-process execution. Roslyn and script dependencies run in a fresh worker; ordinary exceptions or worker exits become tool errors. Scripts exchange JSON with the plugin and receive no live agent objects, DI services or Blazor circuits. The runtime filters inherited environment variables, bounds code/input/output, collects at most 100 artifacts, and attempts temporary-directory cleanup.
Those controls do not restrict filesystem or network permissions. The worker can read or modify files outside OutputDirectory, contact internal services, invoke native functionality, start other processes, or modify shared caches when the host account permits it. A process that deliberately escapes supervision is not contained. The artifact limit bounds what is returned, not how much disk space the script can consume.
For example, removing a database password from the inherited environment does not protect it if the worker can read the password from the host configuration file. OutputDirectory is a convention for returned files, not a filesystem boundary. Exact NuGet versions and disabled #r/#load directives govern dependency preparation, not API permissions. Terminating a worker does not undo external effects.
Supply an external execution boundary
OS-enforced sandbox protections are not available in this release. Untrusted workloads require an external boundary with a restricted identity, limited filesystem and network access, resource quotas and child-process containment.
Until those protections are implemented, provide an external restricted execution boundary for untrusted workloads. Running the host and worker inside the same container still leaves them sharing that container's accessible resources. The boundary must separate script permissions from the host and other workloads. See the C# scripting reference for all current protections and limitations.
Try the complete Surface sales example
The framework SampleApp provisions demo-user:scripting-demo. In Surface, select scripting-demo and ask it to calculate sales revenue by category. GetDemoSales returns three fictional orders; the expected total is USD 400, split into Bikes 250 and Accessories 150. The plugin uses Newtonsoft.Json 13.0.3 and decimal arithmetic.
A report request returns sales-report.json as artifact bytes to the tool caller. Chat summarizes the report; SampleApp does not add artifact hosting or a download-link UI. Its ScriptingDemoTests invoke the blueprint-selected plugin and real worker without model calls. Interactive chat still needs your configured model.
Trace the tool result and create a report
Download the Operations Desk source. The README lists project setup, package prerequisites and local ports.
- Run the previous checkpoint, then use the script and input below as ExecuteCSharp arguments. Inspect Status, Value, Output, Error and Artifacts separately.
- Run the artifact script. Read the returned summary.csv bytes and store them in your application if a user needs a download.
- Pass deliberately invalid C# such as return missingName; and inspect CompilationError plus diagnostics. Correct it and invoke again; each call starts a new process.
- Add the prewarm call before serving agents. Use the same prepared cache path in production and set AllowEnvironmentPreparation=false there after preparation.
var data = JObject.Parse(InputJson);
var total = data["orders"]!.Values<decimal>().Sum();
Console.WriteLine("Calculated in worker " + System.Environment.ProcessId);
return new { Customer = data["customer"]!.ToString(), Total = total };
{"customer":"Eric","orders":[125,75,200]}
var path = System.IO.Path.Combine(OutputDirectory, "summary.csv");
System.IO.File.WriteAllText(path, "Customer,Total\nEric,400\n");
return new { File = "summary.csv", Total = 400 };
using FabrCore.Scripting;
var runtime = app.Services.GetRequiredService<ScriptingRuntime>();
await runtime.PreparePluginAsync<ReportingScriptsPlugin>(app.Services);
dotnet test samples/FabrCore.SampleApp.Tests/FabrCore.SampleApp.Tests.csproj --configuration Release --filter FullyQualifiedName~ScriptingDemoTests
Check success, failure and file lifetime
- Confirm the order script returns Value with Customer Eric and Total 400, while the worker process message appears only in Output. A console message alone is not a structured return value.
- Confirm the artifact result contains summary.csv with the expected CSV content. Store it and verify the application copy remains usable after the worker directory is removed.
- Confirm the invalid script returns CompilationError with useful diagnostics, then rerun a corrected script successfully. Inspect fresh process IDs or reset variables to establish that calls do not share script state.
- With the prepared cache preserved, start production configuration with AllowEnvironmentPreparation=false and run a harmless script. A missing cache should fail initialization instead of restoring packages unexpectedly.
The returned object travels as JSON, not an in-memory reference. Direct plugin callers can inspect the same ScriptExecutionResult the model receives. The application owns durable artifacts and any presentation layer.
If the result is different
WorkerError can mean an unexpected process exit or invalid worker response. TimedOut includes compilation/startup time. Large returns may hit OutputLimitExceeded before a displayed character count suggests, because JSON is bounded in UTF-8 bytes. Reduce the result or store a bounded artifact; do not remove limits to fit a full dataset.
Go deeper
Explore the related documentation.