Skip to content

Hosted TUI Runtime ​

HostedAgentTuiRuntime connects the TUI shell to an ASP.NET Core HPD Agent API. The terminal process becomes a client; the hosted app owns agent definitions, sessions, threads, active runs, and the bidirectional response route.

Map The Hosted API ​

csharp
using HPD.Agent;
using HPD.Agent.AspNetCore;
using HPD.Agent.Providers.OpenAI;
using Microsoft.AspNetCore.Builder;

var builder = WebApplication.CreateBuilder(args);

var dataRoot = Path.Combine(Directory.GetCurrentDirectory(), ".hpd-tui");

builder.Services.AddHPD();
var agent = new AgentConfig { Name = "Hosted TUI Agent" }
    .WithOpenAI(model: "gpt-5-mini")
    .WithInstructions("You are concise and helpful.");

builder.Services.AddHPDAgentRuntime("tui", runtime => runtime
    .AddAgent("tui-agent", agent)
    .WithFileSessionStore(Path.Combine(dataRoot, "sessions"))
    .WithAgentStore(new JsonAgentStore(Path.Combine(dataRoot, "agents"))));

var app = builder.Build();
app.MapGroup("/hpd").MapHPDAgent("tui");
await app.RunAsync();

The server hosts one AgentRuntime named tui, built from the recipe when the server starts. Its one code agent, tui-agent, is its default agent; the TUI names it in its runtime scope. The recipe's stores keep sessions, thread journals, and stored agents on disk across restarts.

The TUI's hosted runtime does not call an in-process AgentRuntime. It sends HTTP requests to the mapped HPD Agent API.

Keep provider composition in the hosted app. The terminal client connects to the mapped API and does not create the model client itself. If the terminal sends typed provider options, give its HostedAgentTuiRuntime the matching generated ProviderComposition so those options survive the HTTP boundary.

Connect The TUI ​

csharp
using HPD.Agent;
using HPD.Agent.TUI;
using HPD.Agent.TUI.Runtime;

if (!HPDApplicationCompositionHost.TryGetApplication(out var application))
{
    throw new InvalidOperationException(
        "A generated HPD application composition is required.");
}

var scope = new AgentTuiRuntimeScope("tui-agent", "local-session", "main");
await using var runtime = new HostedAgentTuiRuntime(new HostedAgentTuiRuntimeOptions
{
    BaseAddress = new Uri("http://127.0.0.1:5057/hpd/"),
    DefaultScope = scope,
    ProviderComposition = application.Providers,
    EventComposition = application.Events
});

await using var tui = HpdAgentTuiApp.Create(
    runtime,
    new DirectAgentTuiExecutionTarget(scope),
    builder => builder
        .AddAgentTuiDefaults()
        .AddSubAgentTui());

await tui.RunAsync();

The TUI executable needs the same generated provider and output-event compositions as the host. The source-generated application composition registers both. A custom event or provider used by the server must also be present in the client composition, or the client cannot serialize inputs or decode the server's event stream. Before it observes a thread, the hosted runtime reads GET /composition/events and refuses to continue when the server's event catalog digest differs from the client's.

Route-Base Warning ​

HostedAgentTuiRuntime uses relative paths such as sessions, agents, and sessions/{sessionId}/threads/{threadId}/inputs.

Set HostedAgentTuiRuntimeOptions.BaseAddress to the HPD Agent API route root, not necessarily the web host root.

If your server maps the API at root:

csharp
app.MapHPDAgent("tui");

use:

csharp
BaseAddress = new Uri("http://127.0.0.1:5057/")

If your server maps the API under a group:

csharp
app.MapGroup("/hpd").MapHPDAgent("tui");

use:

csharp
BaseAddress = new Uri("http://127.0.0.1:5057/hpd/")

Do not point the hosted TUI at http://127.0.0.1:5057/ when the HPD API is actually under /hpd.

Runtime Calls ​

The hosted runtime uses the hosted API for:

  • listing code and stored agents (each with its Source, and the agent's name from config.name), and loading, creating, updating, and deleting stored agents
  • listing, searching, loading, creating, renaming, and deleting sessions
  • listing, creating, forking, renaming, and deleting threads
  • loading authoritative runtime control state with the journal boundary, active run, and pending interactions
  • catching up and observing committed thread events through one resumable SSE stream
  • submitting AgentInputEvent instances
  • cancelling the expected backend-owned execution with structured outcomes
  • sending middleware responses for permissions, continuations, clarifications, and client tools

Hosted TUI middleware responses go through hosted response endpoints. Interactive requests are canonical journal events and also appear in runtime control state while they remain answerable, so a reconnecting TUI can restore its prompt controls before transcript catch-up completes. Bot adapters use their platform-specific callback protocols.

AddSubAgentTui() registers /subagents. It lists the threads the current thread created, with the agent and status of each one's latest execution, and switches to the selected child's sessionId and threadId with that agent, so the user can continue the child conversation after the original delegation finishes.

Thread Projection And Compaction ​

The hosted TUI observes the server's session, thread, and compaction behavior. Its thread-fork API carries the same metadata-oriented fork request supported by the TUI runtime; it does not expose a compaction toggle. Configure fork-target compaction on the backend agent's definition.

Compaction arrives on the same observation stream as an appended THREAD_HISTORY_COMPACTION_CHECKPOINT, which the transcript projection applies. CompactionEvent is lifecycle information; the checkpoint defines the semantic change.

Scope Defaults ​

If DefaultScope is not supplied, HostedAgentTuiRuntime reads GET /agents and starts on the runtime's default agent, or on its only agent when it has one, in session local-session and thread main. A runtime with several agents and no default has no starting agent: resolving the initial target fails and names the agents, so pass a scope that names one. The runtime's registration name is not an agent id.

AgentTuiRuntimeScope requires non-empty agent, session, and thread identifiers. The hosted runtime also rejects malformed endpoint payloads whose required identifier fields are missing or blank; it does not silently construct scopes with empty ids.

Recovery, Active Executions, And Hydration Errors ​

The hosted runtime opens a thread by reading /state, restoring activeExecution and pendingRequests, and capturing observedCursor. It then opens /events?after={sequence}, applies catch-up events in bounded batches, and stays on that stream for future commits. If the stream ends after minutes or hours, it reconnects after the last event the TUI fully applied. Backend work continues independently of the observer connection.

observedCursor describes the coherent server boundary captured with control state. The TUI advances its applied cursor only after the corresponding event handlers complete successfully. Historical, catch-up, and live batches use the same handlers; batching changes redraw cadence, not projection semantics.

Submission returns the authoritative threadExecutionId. The hosted backend remains authoritative if another client starts work.

Enter always submits a UserMessagesInputEvent. While an execution is active, the message joins the running turn, which reads it before its next model request; when the running work cannot take it, it starts the next turn. Double Escape calls IHpdAgentTuiRuntime.CancelExecutionAsync(scope, threadExecutionId, ...), which uses the hosted execution cancellation route; messages the cancelled turn had not read yet are answered in one follow-up turn. A rejected or failed submission is restored to the composer, and a stale TUI never retargets a newer execution automatically.

If an event schema cannot be decoded or projected, hydration stops at the last successfully applied thread position. Register every application-owned event codec in the host and client projection before opening journals that contain that event type.

See Hosted Lifecycle And Recovery for the underlying protocol.

Built for production .NET agent applications.