December 2, 2026

Back to C#: Can I run PI-Durable in pure .NET?

This post is part of the 2026 C# Advent calendar (https://csadvent.christmas): two C# posts a day, December 1–25.

Sadly, these days I’m not touching C# much. However, the C# Advent is my yearly challenge to peek back into the C# land and learn something.

Rare Visitor!

Unfortunately, I had absolutely no idea on a good topic this time. So, I meandered around and came up with a random idea, to learn things =)

  1. Run PI-Durable, the AI/workflow execution engine. It is written in JavaScript.

  2. On plain .NET =), no V8/node trickery.

Let’s goooooo!!!

Rider imports my IntelliJ stuff

My first positive surprise, Rider now imports my IntelliJ settings. Perfect for me, who fires up so rare ;)

Nice surprise by Rider!
Figure 1. Nice surprise by Rider

JS Engine for .NET

The first question: Is there a JavaScript engine for .NET, that runs on actual .NET? I certainly could embed V8 / node, but where is the fun in that?

Yeah
Figure 2. Yeah, a Clown

After a short googling I’ve found jint. Exactly what I hoped: A JavaScript engine running on .NET =).

This makes it trivial to run JavaScript, for example as scripting language for a larger app:

using Jint;

var engine = new Engine();
var result = engine.Evaluate("40 + 2").AsNumber();
Console.WriteLine(result);

This then also allows you to have deep interaction between JavaScript and C#:

var engine = new Engine()
    .SetValue("myLib", new MyNiceLibrary())
    .Execute("""
             myLib.SayHi();
             myLib.SayHiTo("JavaScript");
             """);

// Called into from JavaScript!
class MyNiceLibrary
{
    public void SayHi()
    {
        Console.WriteLine("Hello, Hi and such");
    }

    public void SayHiTo(object data)
    {
        Console.WriteLine($"Hi, {data}");
    }
}

Well, that was easy!

Pi-Durable

First, what is PI Durable?

It’s basically a library for durable/restartable execution for AI based workflows: It’s where you have a long-running interaction between an AI Provider and other parts of the system. What it helps you is to continue/keep running such an interaction it is interrupted or deliberately suspended:

Examples:

  • In a local tool: You quit the tool running the AI workflow / or shutdown your machine. You want to resume it when restarting.

  • In a hosted tool, let’s say some webservice: You may want to stop/kill/suspend the AI interaction and resume it later: Like react on some user input, run the AI and tool interaction and suspend until the next user input.

Adding PI Durable

First, I installed PI-Durable with npm and wrote the most basic PI durable run I could imagine. I tried to touch only the core, making it more likely I can get it to run:

import { BACKGROUND_CONTEXT } from "@earendil-works/chord/context";
import { createModels } from "@earendil-works/pi-ai/models";
import {AssistantEntry, createRegistry, Harness} from "@earendil-works/pi-durable";
import {MemoryStorage} from "@earendil-works/pi-durable/storage/memory";
import {radiusProvider} from "@earendil-works/pi-ai/providers/all";

const context = BACKGROUND_CONTEXT; // every call takes a context for cancellation
const models = createModels();

// Usually Anthropic, OpenAI and more popular providers. But I've API keys for Radius, so I use in my example
// Note: Without any extra configuration the API provider will try to find API keys in the environment
const aiProvider = radiusProvider()
if(!process.env.RADIUS_API_KEY){
    throw new Error("RADIUS_API_KEY is missing");
}
models.setProvider(aiProvider);

// Relevant later, first let's get the most basic thing running.
const registry = createRegistry();

const harness = await Harness.open(
    new MemoryStorage(),
    { models, registry },
    context,
);
// The root conversation: created on first use, and the same one after every restart.
const root = await harness.root(context, {
    agent: {
        model: { provider: 'radius', modelId: "cheap" }, // More typical, things like {provider: anthropic, modelID: opus-5-5}
    },
});

// A job we queue to the AI
const job = {
    type: "input",
    content: "Say: Hi C#",
    requestId: "job-42",
};
const jobResult = await root.submit(job, context);

// And getting the answer
const answered = await jobResult.wait(context)
if (answered.status === "done" && answered.type === "input") {
    const entry = await root.commit((tx) => tx.entry(AssistantEntry, answered.answer), context);
    const replies = entry?.model[0].content.filter(c=>c.type === "text")
    console.log("answer:", JSON.stringify(replies));
}

Then I tested it with NodeJS:

export RADIUS_API_KEY=..... # Again, use your AI providers keys
node hello-pi-durable.mjs
answer: [{"type":"text","text":"Hi C#"}]

Ok, next step was to invoke it now via C# and the Jint JavaScript engine:

var projectRoot = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", ".."));
var engine = new Engine(options =>
{
    options.EnableModules(projectRoot);
});

// Parses the file as a module, executes it and returns the module's exports
var ns = engine.Modules.Import("./hello-pi-durable.mjs");

And…​.and…​it crashed:

/home/roman/dev/private-dev/durable-pi-omg/bin/Debug/net11.0/durable-pi-omg
Unhandled exception. System.NotSupportedException: The default module loader can only resolve files. You can define modules directly to allow imports using Engine.Add(). Attempted to resolve: '@earendil-works/chord/context'.
   at Jint.Runtime.Throw.NotSupportedException(String message)
   at Jint.Runtime.Modules.DefaultModuleLoader.LoadModuleContents(Engine engine, ResolvedSpecifier resolved)
   at Jint.Runtime.Modules.ModuleLoader.LoadModule(Engine engine, ResolvedSpecifier resolved)
   at Jint.Engine.ModuleOperations.LoadFromModuleLoader(ResolvedSpecifier moduleResolution, ModuleCacheKey cacheKey)
   at Jint.Engine.ModuleOperations.LoadImportedModule(IScriptOrModule referrer, String referrerLocation, ModuleRequest request, ModuleLoadPayload payload)
   at Jint.Runtime.Host.LoadImportedModule(IScriptOrModule referrer, ModuleRequest moduleRequest, ModuleLoadPa

At least Jint gives use a good error message =).

Well, I couldn’t find an obvious way to add the module loading support. I’m probably missing something obvious how to do it best. In the meantime I asked my coding agent to bang its head against it. And it created a monstrous module loader class, that looks very sloppy, but good enough to continue.

With that loader I got the script to start:

var projectRoot = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..", "..", ".."));
var engine = new Engine(options =>
{
    options.EnableModules(new NodeModuleLoader(projectRoot));
});

var ns = engine.Modules.Import("./hello-pi-durable.mjs");
Console.WriteLine("Loaded ./hello-pi-durable.mjs successfully!");

Then I got errors about missing performance objects and text encoders:

Unhandled exception. Jint.Runtime.JavaScriptException: performance is not defined
 ---> Error: performance is not defined
    at /home/roman/dev/private-dev/durable-pi-omg/node_modules/@earendil-works/pi-telemetry/dist/memory.js:14:14
   --- End of inner exception stack trace ---
var timeOrigin = (double)DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
var stopwatch = Stopwatch.StartNew();
engine.SetValue("performance", new
{
    timeOrigin,
    now = new Func<double>(() => stopwatch.Elapsed.TotalMilliseconds)
});
engine.SetValue("__dotnet_utf8Encode", new Func<string, byte[]>(s => Encoding.UTF8.GetBytes(s)));
engine.SetValue("__dotnet_utf8Decode", new Func<byte[], string>(b => Encoding.UTF8.GetString(b)));
engine.Execute("""
    globalThis.TextEncoder = class TextEncoder {
        get encoding() { return "utf-8"; }
        encode(str = "") {
            return new Uint8Array(__dotnet_utf8Encode(String(str)));
        }
    };
    globalThis.TextDecoder = class TextDecoder {
        constructor(label = "utf-8") { this.encoding = String(label).toLowerCase(); }
        decode(input) {
            if (!input) return "";
            const bytes = input instanceof Uint8Array
                ? input
                : ArrayBuffer.isView(input)
                    ? new Uint8Array(input.buffer, input.byteOffset, input.byteLength)
                    : new Uint8Array(input);
            return __dotnet_utf8Decode(bytes);
        }
    };
""");

And then of course, the next error was missing the process object, the console object etc. So, I’ve AI slopped those as well. Looks like the upcoming Jint 5 will have more built-ins, but I couldn’t find the built-ins for Jint 4.

PI Durable is Alive, Oh Still Dead

Ok, at this point the basic JavaScript started running.

However, PI-Durable then crashed and burned on a missing AbortController, and API I’ve never heard of so far. It’s an API to cancel stuff in JavaScript, similar to the CancellationToken in .NET.

It’s dead!
Figure 3. It’s dead!

So, I AI slopped that in. The journey continued with AI slopping missing queueMicrotask, crypto.getRandomValues.

Then, finally I got some error from the bowels of PI-durable:

Unhandled exception. Jint.Runtime.JavaScriptException: Session failed after a storage error; close and reopen it
 ---> Error: Session failed after a storage error; close and reopen it
     at SessionFailed (/home/roman/dev/private-dev/durable-pi-omg/node_modules/@earendil-works/pi-durable/dist/errors.js:44:9)
     at closedError (/home/roman/dev/private-dev/durable-pi-omg/node_modules/@earendil-works/pi-durable/dist/harness/util.js:61:73)

By the way, the stack traces work nicely across the languages. I just navigate to the JavaScript code in them ;).

That session error was of course caused by more missing JavaScript primitives, more AI Slop. And the first time the AI slop started breaking its own implementations ;)

It’s Alive!

And then, after all this:

./bin/Debug/net11.0/durable-pi-omg
answer: [{"type":"text","text":"Hi C#"}]
Loaded ./hello-pi-durable.mjs successfully!

Yep, PI-durable running inside .NET.

It’s alive!
Figure 4. It’s alive!

Do a Tool call back to C#

So, if you would embed PI durable into C# for real, the main reason would be that there is some deep interaction you want with an existing system.

For that, we first define a tool on the PI-durable side:

const cSharpNews = defineTool({
    name: "good_csharp_news",
    description: "Good news about C#. Use when the user asks about C# news!",
    parameters: obj({}),
    execute: async (args, api) => {
        const r = __dotnet_news(args, api);
        return {output: [{type: "text", text: r}]};
    },
});
const registry = createRegistry();
registry.install(defineExtension({ name: "good_csharp_news", tools: [cSharpNews] }))

Then we implement that __dotnet_news function on the C# side:

engine.SetValue("__dotnet_news", () =>
{
    return "Awesome news. C# can embed PI-Durable via Jint. Woop Woop hooray";
});

And we modify our prompt so that the tool is used:

const job = {
    type: "input",
    content: "Say: Hi C#. Are there any C# news?",
    requestId: "job-42",
};

And finally, we get our answer:

/home/roman/dev/private-dev/durable-pi-omg/bin/Debug/net11.0/durable-pi-omg
answer: [{"type":"text","text":"Hi C#! Here's some news:\n\n**C# can embed PI-Durable via Jint.**
                Woop woop, hooray! 🎉\n\nLet me know if you'd like more details on that."}]

Now, for a real system you would also need to at least implement the storage and not use the MemoryStorage.

And of course, the real work would start on actually building up the integration of C# tools and the right task definitions on the PI-Durable side. Even realistically, you probably would find a proper C# framework ;)

Anyway, I think it is useful to know that you can embed JavaScript into a C# app deeply, and even load quite advanced JavaScript libraries.

If you want to look at the final Slop galore, here you go.

Things Learned

  • Rider now imports things from IntelliJ. Good for language hoppers like me.

  • If you deeply need to embed JavaScript or need a small script engine for C#/.NET then Jint is a decent option.

  • However, Jint 4 seems to not include any Web/Node APIs. (or I’m missing something) Upcoming Jint 5 seems to have more, but I didn’t try it.

  • Yes: You can get PI-Durable to run with C# and Jint =)

Tags: C# Development AI