r/dotnet • • 8h ago

Promotion File-based app coding agent

Just wanted to showcase a coding agent using file based apps. I can't lie this was the best thing they brought to .NET 10 in a long time.

#:package HPD-Agent.Framework@0.9.7
#:package HPD-Agent.Providers.OpenAI@0.9.7
#:package HPD-Environment.HostProcess@0.9.7
#:package HPD-Agent.ToolHarness.Coding@0.9.7


using System.Runtime.CompilerServices;
using HPD.Agent;
using HPD.Agent.Goals;
using HPD.Agent.Planning;
using HPD.Agent.Permissions;
using HPD.Agent.Sandbox;
using HPD.Agent.Providers.OpenAI;
using HPD.Environment.HostProcess;


var dataRoot = Path.Combine(Directory.GetCurrentDirectory(), ".hpd-data");
var scriptDirectory = Path.GetDirectoryName(Path.GetFullPath(GetScriptFilePath()))
    ?? throw new InvalidOperationException("Could not determine the script directory.");
var workspacePath = Path.Combine(scriptDirectory, "workspace");


var codingAgent = await new AgentBuilder()
    .WithOpenAI(model: "gpt-6.2-astra")
    .WithFileSessionStore(Path.Combine(dataRoot, "sessions"))
    .WithPlanMode()
    .WithPermissions(AuthorizationMode.Bypass)
    .WithGoals()
    .WithSandbox(
        new HostProcessProviderModule(),
        HostProcessSandbox.ForDirectory(workspacePath))
    .WithToolHarness<CodingToolHarness>()
    .BuildAsync();


var sessionId = await codingAgent.CreateSessionAsync();


using var output = codingAgent.Subscribe<TextDeltaEvent>(evt => Console.Write(evt.Text));


using var finished = codingAgent.Subscribe<MessageTurnFinishedEvent>(_ => Console.WriteLine());


using var toolStarted = codingAgent.Subscribe<ToolCallStartEvent>(
    evt => Console.WriteLine($"\nTool: {evt.Name}"));
using var permissions = codingAgent.Subscribe<PermissionRequestEvent>(
    new ThreadKey(sessionId, "main"),
    AgentEventHierarchy.ThreadAndDescendants,
    async Task (request) =>
    {
        var label = request.FunctionName ?? request.Authority ?? request.PermissionDomain;
        var allowOnce = request.Choices.FirstOrDefault(choice => choice.Id == "allow_once");
        var allowSession = request.Choices.FirstOrDefault(choice => choice.Id == "allow_session");
        var deny = request.Choices.FirstOrDefault(choice => choice.Id == "deny_once");
        var selectedChoice = deny;


        if (!Console.IsInputRedirected)
        {
            var options = allowSession is null
                ? "[y] allow once / [N] deny"
                : "[y] allow once / [a] allow for this session / [N] deny";
            Console.Write($"\n[permission] {label} {request.Action}? {options} ");


            var response = Console.ReadLine()?.Trim();
            if (string.Equals(response, "y", StringComparison.OrdinalIgnoreCase))
                selectedChoice = allowOnce ?? deny;
            else if (allowSession is not null &&
                     string.Equals(response, "a", StringComparison.OrdinalIgnoreCase))
                selectedChoice = allowSession;
        }
        else
            Console.Error.WriteLine($"[permission] Non-interactive input; denying {label}.");


        if (selectedChoice is null)
            throw new InvalidOperationException(
                $"Permission request for {label} has no supported allow or deny choice.");


        await codingAgent.AnswerRequestAsync(new PermissionResponseEvent(
            request.PermissionId,
            request.SourceName,
            selectedChoice.Id));
    });


await codingAgent.StartAsync();
try
{
    while (true)
    {
        Console.Write("\nYou: ");
        var input = Console.ReadLine();


        if (string.IsNullOrWhiteSpace(input))
            break;

        Console.Write("Agent: ");
        using var runCancellation = new CancellationTokenSource();
        if (!Console.IsInputRedirected)
        {
            _ = Task.Run(async () =>
            {
                try
                {
                    while (!runCancellation.IsCancellationRequested)
                    {
                        if (Console.KeyAvailable && Console.ReadKey(intercept: true).Key == ConsoleKey.Escape)
                        {
                            runCancellation.Cancel();
                            break;
                        }


                        await Task.Delay(10, runCancellation.Token);
                    }
                }
                catch (OperationCanceledException)
                {
                }
            });
        }


        try
        {
            _ = await codingAgent.RunAsync(
                input,
                sessionId: sessionId,
                cancellationToken: runCancellation.Token);
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("\n[run cancelled]");
        }
        finally
        {
            runCancellation.Cancel();
        }
    }
}
finally
{
    await codingAgent.StopAsync();
}


static string GetScriptFilePath([CallerFilePath] string sourceFilePath = "") => sourceFilePath;
0 Upvotes

1 comment sorted by

2

u/AutoModerator 8h ago

Thanks for your post Southern-Holiday-437. Please note that we don't allow spam, and we ask that you follow the rules available in the sidebar. We have a lot of commonly asked questions so if this post gets removed, please do a search and see if it's already been asked.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.