59 KiB
Coding-Agent Application Hosts and Plugin Facets
Status: Tentative design input, not a normative contract or implementation handoff. The examples use illustrative APIs that do not exist yet. Reconcile this design with
rpc.md,telemetry.md, and the final harness contract before adding it toharness.mdor creating a work package.
This document assumes you already understand AgentHarness, AgentLane, Session, SessionTree, SessionRepo, invocation Context, and telemetry. Read rpc.md for wire frames, remote references, subscriptions, and trace carriers, and telemetry.md for context propagation and cancellation semantics.
Bird's-eye view
The new coding agent is assembled from an ordered plugin manifest, not a monolith with an extension API bolted on. Three layers:
- The plugin kernel owns generic lifecycle mechanics: ordered setup, activation, scoped resource ownership, failure rollback, and reverse-order disposal. It knows nothing about Harness, tools, TUI components, RPC services, connections, or coding-agent policy.
- An application host owns one concrete runtime and constructs the plugin bindings for that runtime. The session host normally runs in a dedicated session worker and owns session authority — the real Harness. A presentation host (TUI today, web later) owns a user interface. A server host owns server-wide authority: session records (
SessionRepo), session-worker management, authentication, attachment, and routing between presentations and session workers. - A plugin package implements one feature as one or more host-specific facets — setup functions, one per host kind. Each facet receives only the bindings natural to its host instance and process.
The initial topology has one server and no server-to-server links:
server
├─ TUI A
├─ web B
├─ session worker S0
└─ session worker S1
A presentation and a session worker each connect to the server. There is no direct presentation→session-worker connection; the server routes service calls to the selected worker. The server lists and manages only its own sessions. Multi-server routing and server hierarchies are out of scope.
A session worker normally owns one session, and each session facet is instantiated for that session. A server facet is instantiated once per server process and is shared across every session and presentation connected to it. Server facets should therefore be rare and limited to inherently server-wide concerns. Per-session feature state belongs in session facets; dedicated workers provide the preferred lifecycle, crash, and state isolation. Future co-location may preserve the same logical bindings without changing what objects a facet can access.
Host and client are roles per connection, not fixed process kinds. The server hosts presentation and session-worker connections. A session worker serves its provided session services and may consume server-provided services over the same RPC binding mechanism. "Client" below always names the connection role, never a kind of plugin.
Why this shape
- Authority stays where it belongs. Provider credentials, tool execution, and per-session plugin data exist only in the session worker; session records and worker control exist only in the server. Nothing reaches a presentation except through a deliberate contract.
- One feature stays coherent. The question plugin's tool, dialog, and renderer ship in one package around one JSON contract, yet each facet is host-native code.
- A new surface is presentation-only work. A web facet for the question dialog or the session picker registers against existing tokens; session and server code do not change.
- Server state stays server-wide. A server facet is shared by all sessions and clients, so features use one only when their authority is inherently global to that server.
- No privileged built-ins. Built-ins and third-party plugins receive identical bindings, so shipping the product continuously exercises the extension API.
- Testable in pieces. A facet tests against its host bindings, a contract against loopback, and a routed TUI → server → session-worker path against a real transport — independently.
One feature, several host facets
A coding-agent plugin is a feature bundle that may provide a facet for any host:
interface CodingAgentPlugin {
readonly id: string;
readonly server?: PluginFacet<CodingAgentServerPluginContext>;
readonly session?: PluginFacet<CodingAgentSessionPluginContext>;
readonly tui?: PluginFacet<CodingAgentTuiPluginContext>;
readonly web?: PluginFacet<CodingAgentWebPluginContext>;
}
type PluginFacet<PluginContext> = (context: PluginContext) => void | Promise<void>;
PluginFacet is the only plugin-facing shape the generic kernel needs; the facet names and context types belong to the coding-agent application. Facets are optional: a models.json plugin has only a session facet, a terminal theme only a TUI facet, the session directory a server facet plus a TUI facet. Examples use an illustrative definePlugin() helper returning a CodingAgentPlugin — the loaded, in-process shape.
A package keeps shared wire contracts separate from host dependencies:
question-plugin/
contract.ts JSON DTOs and service tokens
session.ts pending-question authority and tool contribution; imports agent/session code
tui.ts terminal dialog and renderer; imports TUI code
web.ts optional browser dialog and renderer
index.ts loopback bundle; production hosts resolve per-host entry points
The browser build never imports session.ts; the session process never imports TUI or DOM code.
The question plugin is this document's end-to-end example:
model calls the question tool (session facet)
→ session facet records one pending question (session authority)
→ every connected TUI/web facet observes and opens it (shared service)
→ the first accepted answer settles it for everyone
→ session facet returns the durable tool result
→ presentation facets close the dialog and render the result
With no presentation connected, the question remains pending. A TUI or web facet that connects later obtains the same pending question.
The models service in the next sections illustrates services and replicated state; the server section covers server-wide services and session routing; the question section makes the full round trip concrete.
Starting and connecting hosts
Every host receives the same logical manifest: JSON-safe plugin identity, order, and version. It resolves only its own package entry points (./server, ./session, ./tui, or ./web); a missing entry point means that plugin has no facet for the host. Resolution, not convention, enforces the dependency boundary.
const manifest: PluginManifestEntry[] = [
{ id: "@pi/session-core" },
{ id: "@pi/providers-builtin" },
{ id: "@pi/question" },
];
Presentation and session-worker hosts do not discover servers or open sockets themselves. They receive one connection function; the server host receives a listener:
type Connect = (signal: AbortSignal) => Promise<Transport>;
type Listen = (accept: (transport: Transport) => void) => () => void;
interface Transport {
send(frame: JsonValue): void;
receive(listener: (frame: JsonValue) => void): void;
close(): void;
readonly closed: Promise<void>;
}
Connect performs one connection attempt. Its closure owns the endpoint and credential, so the host never reads an address, environment variable, or secret. Listen lets the server accept presentation and session-worker connections. Both operate on the same bidirectional framed Transport.
declare const tuiAppHost: {
start(options: { manifest: Manifest; connect: Connect }): Promise<RunningHost>;
};
declare const sessionAppHost: {
start(options: { manifest: Manifest; connect: Connect; identity: SessionIdentity }): Promise<RunningHost>;
};
declare const serverAppHost: {
start(options: { manifest: Manifest; listen: Listen }): Promise<RunningServer>;
};
interface RunningHost {
readonly connection: RemoteState<ConnectionState>;
stop(): Promise<void>;
}
interface RunningServer {
readonly local: Connect; // connect another host in the same process
stop(): Promise<void>;
}
Every deployment uses those three entry points:
// separate processes
await serverAppHost.start({ manifest, listen: listenSocket(socketPath) });
await sessionAppHost.start({ manifest, identity, connect: dialSocket(endpoint, token) });
await tuiAppHost.start({ manifest, connect: dialSocket(endpoint, token) });
// standalone: the same hosts and boundaries, without sockets
const server = await serverAppHost.start({ manifest, listen: listenNothing() });
await sessionAppHost.start({ manifest, identity, connect: server.local });
await tuiAppHost.start({ manifest, connect: server.local });
This keeps deployment policy outside plugins:
- reconnecting means calling
connect(signal)again; the host owns retry timing, whileConnectowns one attempt; - the accepting server assigns peer identity during its handshake from the presented credential;
SessionIdentityidentifies the durable session being run, not a trusted claim about the connection; server.localmakes standalone a deployment, not a separate mode or code path.
The only connection state exposed to facets is:
type ConnectionState =
| { status: "connecting"; attempt: number }
| { status: "connected"; since: string }
| { status: "disconnected"; since: string; reason: string; retryAt: string | null };
After transport setup, each host asks the kernel to create one lifecycle scope per selected facet, builds its host-specific bindings, and invokes the facet:
interface PluginLifecycleScope {
onActivate(callback: () => void | Promise<void>): void;
onDispose(callback: () => void | Promise<void>): void;
own(disposal: () => void | Promise<void>): void;
}
Host infrastructure calls own() for every service, contribution, or subscription registered through facet bindings. Facets first register in manifest order; then onActivate callbacks start effects and the host exposes state snapshots. Failure and normal shutdown dispose scopes in reverse order. Duplicate services, missing dependencies, and dependency cycles are application-assembly errors.
The prototype in packages/coding-agent/test/fixtures/plugin-app/ demonstrates the composition model with an ad hoc RPC implementation; the shared RPC design in rpc.md should replace that transport without replacing the host/facet architecture.
One process owns one session, and session authority never migrates. Each presentation and session worker has one multiplexed connection to its server; plugins never open private sockets. Plugin authors never implement request IDs, sockets, trace carriers, cancellation frames, remote-reference registries, or reconnect buffering.
Out of scope: arbitrary object remoting, serialized functions/classes/Map/Set, remote hook or tool execution, offline presentation writes or automatic mutation replay, a universal remote AgentHarness or serialized UI tree, and re-exposing forwarded frames, proxies, or references as plugin-visible objects.
Services connect host facets
Facets communicate across processes through services. A service token is a typed identity plus trusted exposure metadata for the generic RPC layer:
function defineRemoteService<T>(id: string, exposure?: ServiceExposure<T>): RemoteService<T>;
The exact exposure-descriptor API belongs to rpc.md; examples use state, events, and results only to illustrate the required capabilities.
The models service — the authority behind the model picker and thinking-level control — exercises methods, replicated state, and multiple consumers.
Shared contract
export interface ModelRef {
provider: string;
modelId: string;
}
export interface ModelsState {
catalog: { revision: number; availableModels: Array<ModelRef & { name: string; reasoning: boolean }> };
configuration: { model: ModelRef | null; thinkingLevel: "off" | "low" | "high" };
refresh:
| { status: "idle" | "refreshing" | "done" }
| { status: "warning"; errors: Record<string, string> };
}
export interface ModelsService {
readonly state: RemoteState<ModelsState>;
cycleThinking(context: Context): Promise<void>;
refresh(context: Context): Promise<void>;
select(model: ModelRef, context: Context): Promise<void>;
}
export const Models = defineRemoteService<ModelsService>("models", { state: ["state"] });
Everything in a contract is strict JSON: arguments, results, replicated state, events. That is why state uses null, never undefined. Context is control-plane data in a declared position; the proxy strips it and it is never serialized.
Session facet
export const providersBuiltin = definePlugin({
id: "@pi/providers-builtin",
session(pluginContext: CodingAgentSessionPluginContext) {
const providers = new ProviderRegistry(); // process-local, non-JSON
const state = pluginContext.remoteState<ModelsState>(initialModelsState());
pluginContext.provide(Models, {
state,
async select(model, context) {
const spec = findSpec(state.value.catalog, model);
if (spec === undefined) throw new Error(`Unknown model: ${model.provider}/${model.modelId}`);
const thinkingLevel = spec.reasoning ? state.value.configuration.thinkingLevel : "off";
state.set({ ...state.value, configuration: { model, thinkingLevel } }, context);
},
async refresh(context) {
state.set({ ...state.value, refresh: { status: "refreshing" } }, context);
const errors = await providers.refresh(context.abortSignal);
state.set({ ...state.value, catalog: providers.snapshot(), refresh: toRefreshStatus(errors) }, context);
},
// cycleThinking is analogous: read configuration, state.set(next, context)
});
pluginContext.onActivate(() => providers.rebuild());
},
});
TUI facet
export const modelSelection = definePlugin({
id: "@pi/model-selection",
async tui(pluginContext: CodingAgentTuiPluginContext) {
const models = await pluginContext.session.use(Models);
pluginContext.commands.register("models.select", (ctx, model: ModelRef) => models.select(model, ctx));
models.state.subscribe((next) => renderModelSelector(next));
},
});
The TUI facet has no credentials, registry, or refresh logic: it calls a typed proxy — a generated object with the contract's method signatures whose calls become RPC — and renders replicated state. A web facet would do the same through the web host context.
Service semantics
A service has one owner and many consumers: providersBuiltin provides Models; the model picker and the thinking-level control (one command bound to ctrl+t) both consume it.
use() has two modes:
- Local: in the process that provides the service,
use()is synchronous and returns the actual implementation object. No serialization, no proxy. - Remote: across a connection,
use()is asynchronous and demand-driven: it subscribes to the service on first demand and resolves a typed proxy. Concurrent consumers of one token in one process share one proxy, one state replica, and one remote subscription.
Presentation facets consume remotely through two explicit namespaces — server.use() and session.use(), defined below. Session facets consume their own process's services locally and server services remotely through server.use(). provide(), use(), and remoteState() are host infrastructure layered over the kernel scope, not kernel API.
What each host context grants
This is the most important boundary in the design.
Session facets run beside the real thing. They execute in the process that owns the concrete AgentHarness, AgentLane, Session, and SessionTree, and receive direct, process-local, scoped capabilities backed by those instances — not RPC proxies. Calls preserve real method signatures, Context propagation, Result types, and object identity. A session facet never RPCs back into its own process.
interface AgentPluginScope {
readonly identity: SessionIdentity; // sessionId + workspaceId
readonly main: AgentLanePluginView;
lane(name: string, context: Context): Promise<AgentLanePluginView | undefined>;
readonly sessionTree: SessionTree;
readonly hooks: ScopedHooks;
readonly events: ScopedEvents;
}
interface CodingAgentSessionPluginContext extends PluginLifecycleScope {
readonly agent: AgentPluginScope; // scoped local session authority
// service/state infrastructure (session-host owned)
provide<T>(service: RemoteService<T> | LocalService<T>, implementation: T): void;
use<T>(service: RemoteService<T> | LocalService<T>): T;
remoteState<T extends JsonValue>(initial: T): MutableRemoteState<T>;
remoteEvents<T extends JsonValue>(): MutableRemoteEvents<T>;
readonly server: ServerServices; // remote access to the managing server
// contribution registries (session-host owned)
readonly providers: ProviderContributionRegistry;
readonly tools: ToolContributionRegistry;
// reverse interactions and attached-client lifecycle
readonly interactions: SessionInteractions;
onClientAttach(callback: (clientId: string) => void): void;
onClientDetach(callback: (clientId: string) => void): void;
}
"Local" and "unrestricted" are separate decisions. The scope narrows authority for lifecycle and composition — hooks and event subscriptions registered through it are automatically owned by the plugin and disposed with it — but sessionTree may be the actual local derived object. The host keeps the unrestricted concrete instances and reserves: AgentHarness.close() and Session.close(); raw Session.mutate() and SessionMutator (unless a narrowly trusted durability plugin explicitly owns them); idGenerator and backend/storage objects; whole-registry setters such as setTools(); unscoped hook/event registration; transport exposure and remote-reference registration. This is a composition and lifecycle boundary, not a security sandbox: session facets are trusted code in the authoritative process. The manifest may explicitly grant broader local capability, but built-ins receive no implicit bypass.
Presentation facets hold none of this. A TUI or web facet never receives the raw Harness, Session, tree, tool registry, hooks, or credentials — not even as proxies. It receives only what a session or server facet deliberately exposes: semantic service proxies, replicated state, and semantic events/interactions.
interface ServerServices {
use<T>(service: RemoteService<T>): Promise<T>; // terminates at the connected server
readonly connection: RemoteState<ConnectionState>;
}
type AttachmentState = { status: "detached" } | { status: "attaching" | "attached" | "degraded"; sessionId: string };
interface SessionServices {
use<T>(service: RemoteService<T>): Promise<T>; // forwarded to the one selected session
readonly attachment: RemoteState<AttachmentState>;
}
interface CodingAgentTuiPluginContext extends PluginLifecycleScope {
readonly server: ServerServices; // two explicit remote namespaces
readonly session: SessionServices;
readonly interactions: PresentationInteractions;
// terminal-specific facilities and contribution registries
readonly ui: TuiFacilities; // select/input dialogs, overlays, focus
readonly commands: CommandContributions;
readonly keybindings: KeybindingContributions;
readonly toolRenderers: ToolRendererContributions;
readonly slots: SlotContributions;
}
The two namespaces are the topology made visible: server.use(SessionDirectory) resolves a service the connected server provides itself; session.use(Models) resolves a service of the one selected session — the session this presentation is currently attached to. A presentation has at most one selected session. session.use() resolves its shared proxy immediately; while detached, calls fail with not_attached and no state is present. The two namespaces fail independently: the server connection can be healthy while the selected session is unreachable (attachment.status === "degraded").
A future CodingAgentWebPluginContext carries the same two namespaces plus browser registries — routes, views, DOM dialogs. The server context is defined in the server section. Contexts resemble each other by convention; no kernel-owned base type forces the shape.
Concretely, a chat plugin exposes a narrow Chat contract — prompt(request, context) returning { accepted, operationId, error }, plus requestAbort(operationId, context) — and implements it with direct local lane capabilities:
session(pluginContext: CodingAgentSessionPluginContext) {
const lane = pluginContext.agent.main;
pluginContext.provide(Chat, {
async prompt(request, context) {
return toPromptResponse(await lane.prompt(request.message, context));
},
async requestAbort(operationId, context) {
await lane.requestAbort(operationId, context);
},
});
}
Its TUI facet consumes Chat through session.use() exactly as the model picker consumes Models. Neither reveals the Harness object behind them; there is no universal remote Harness for arbitrary plugins. rpc.md may still define generic Harness proxies for other trusted integrations (an IDE bridge, an orchestrator) — deliberate, separate exposures, not the plugin boundary.
Local services and narrow remote facades
Not every dependency should be remotely reachable. A local service is a token confined to its providing process. It may hold functions, native objects, credentials, or filesystem handles; remote use() cannot resolve it, and local services are never discoverable remotely. The pattern for sensitive state is a local full service plus a narrow remote facade:
const Credentials = defineLocalService<CredentialStore>("credentials"); // get/set provider secrets
interface AccountsService {
readonly state: RemoteState<{ providers: Array<{ provider: string; configured: boolean }> }>;
remove(provider: string, context: Context): Promise<void>;
}
const Accounts = defineRemoteService<AccountsService>("accounts", { state: ["state"] });
The auth plugin's session facet uses Credentials directly; presentations see provider IDs and configured booleans — never secrets. If some settings must not be remotely writable, split them the same way; do not rely on presentation-side convention.
Replicated state: RemoteState
ModelsService.state is a RemoteState<ModelsState>: authoritative latest-value replication — not event history, durable storage, a CRDT, or a multi-writer mechanism.
interface RemoteState<T> {
readonly value: T;
subscribe(listener: (value: T, context: Context) => void): () => void;
}
interface MutableRemoteState<T> extends RemoteState<T> {
set(value: T, context: Context): void;
}
Required behavior:
- The providing host owns the one authoritative value; remote consumers call methods rather than writing the replica.
- Every replica has a local initial value. A facility may declare one; otherwise it is JSON
null.subscribe()immediately reports that current local value even before hydration, keeping local and remote subscription behavior consistent. The state type must includenullwhen no non-null initial value is declared. - Hydration — installing a complete snapshot of all exposed state values atomically before updates flow — happens when a consumer first subscribes; subscribing before hydration is valid, and updates emitted meanwhile are buffered, so a client observes initial-value, snapshot, then updates with no gap.
- The client replica retains its latest local value. After hydration, client
.valueis synchronously readable andsubscribe()immediately reports the current value, then future updates. The immediate pre-hydration callback uses a local lifecycle context; a hydrated snapshot callback uses a fresh hydration context parented to the subscription, because the write that produced the value may be long settled. - Values are detached with structured JSON semantics; one listener cannot mutate another's state.
- Reconnect or reattach replaces client state from a fresh authoritative snapshot; disconnect retains the last value as stale display data alongside the connection/attachment state.
set(value, context)carries source trace metadata; each delivery invokes listeners with a reconstructed deliveryContext. Background updates use an intentional background or lifecycle context, never a retained caller context.
Anything a consumer must recover after reconnect is exposed as remote state or pulled through a remote method. Remote state is latest-value replication, not by itself durable session storage; the providing facet must reconstruct its authoritative value after a worker restart.
Prefer several coarse independent cells over one giant value or a universal patch language, so a catalogue refresh does not retransmit unrelated configuration. High-frequency data such as transcript streaming should use semantic deltas plus a final authoritative replacement. Revision metadata, gap recovery, unchanged-value suppression, and demand-driven subscription are protocol concerns, not plugin-author concerns.
Contribution registries: many contributors, one result
Services fit one owner, many consumers. Providers and tools invert that: many plugins contribute to one host-owned result. A mutable global registry would make composition order-dependent and removal impossible. A contribution registry instead replays ordered contributions over a fresh draft:
fresh ProviderDraft
→ built-in provider contribution (@pi/providers-builtin)
→ remote catalogue contribution (@pi/providers-catalog)
→ models.json transformation (@pi/providers-models-json)
→ authentication/availability marking (@pi/auth)
→ validated ProviderState
Removing a plugin removes its contribution and rebuilds; nothing runs an inverse mutation. Tools follow the same model, including wrapping:
sessionContext.tools.add((draft) => {
draft.set("review_add", reviewAddTool);
draft.wrap("bash", (next) => async (invocation) => {
await authorize(invocation);
return next(invocation);
});
});
Ordered wrappers compose deterministically — telemetry(permission(sandbox(coreBash))) — and if the permission plugin disappears, rebuilding yields telemetry(sandbox(coreBash)). Only the host finalizes the draft and applies the complete registry to the Harness; plugins never call setTools(). Contributions configure rebuilt behavior; hooks intercept live operations — separate mechanisms.
Context, cancellation, and telemetry for plugin authors
rpc.md and telemetry.md own the mechanisms. What a plugin author needs to know:
- Every remote method receives a
Contextin its declared position. The proxy strips it from the JSON arguments and uses it to parentrpc.client, inject the trace carrier, and mapcontext.abortSignalto request cancellation. - The server never deserializes the client's context. It constructs a fresh one: a request-local abort signal, a telemetry parent extracted from the trace carrier, and server-created typed values such as the authenticated client identity. Clients cannot smuggle context values across.
- No receiver-level defaults: shared service objects never retain a caller's context.
The model refresh shows the whole author-visible surface:
const controller = new AbortController();
await uiTelemetry.startSpan({ name: "ui.models.refresh" }, async (span) => {
const context = withAbortSignal(controller.signal, withTelemetryContext(span, BACKGROUND_CONTEXT));
await models.refresh(context);
});
The implementation may open its own span for lower work, producing the distributed trace:
ui.models.refresh
└─ rpc.client models.refresh
└─ rpc.server models.refresh
└─ plugin.models.refresh
controller.abort() cancels only that one request: the server's reconstructed context.abortSignal aborts, and no other caller is affected.
Three cancellation domains must never blur:
- Invocation cancellation aborts one remote call or wait — the
controller.abort()above. - Service-owned cancellation is an explicit method such as
job.cancel()that stops a service-owned task. - Durable Harness cancellation —
requestAbort()/abort()— writes durablecancel_requestedand drives durable settlement.
A transport disconnect performs only the first for active requests and closes that client's subscriptions. It must not silently cancel service-owned work or write durable cancellation. Work intended to outlive its initiating request must deliberately detach into a service-owned task with its own controller and telemetry root.
Events
A remotely exposed event source is a projection of host-local events, not a remotely invoked callback. A Git plugin:
interface GitService {
readonly status: RemoteState<GitStatus>;
readonly events: RemoteEvents<GitEvent>; // { type: "status_changed" | "head_changed" }
refresh(context: Context): Promise<void>;
}
const Git = defineRemoteService<GitService>("git", { state: ["status"], events: ["events"] });
Server-side, the exposure adapter subscribes to the host-local source once per remote subscription and forwards frames. Client-side, events is a local facade whose listeners run in the client process — callbacks never cross the wire; on(type, listener) filters by discriminator, subscribe(listener) observes everything. Each event carries source trace metadata from the providing host's context, so client-side handling stays correlated with the originating operation. The adapter owns subscribe/unsubscribe frames, sequencing, buffering, flow control, and disconnect cleanup (rpc.md). Remote events are non-durable and never replayed: a new or reconnected consumer sees only events emitted after its subscription becomes active. Anything needed to reconstruct current behavior after reconnect belongs in remote state or a pull method.
Service-owned jobs
Long-running work should return a capability rather than one method that blocks indefinitely:
interface IndexJob {
readonly progress: RemoteState<IndexProgress>;
wait(context: Context): Promise<IndexProgress>; // aborting this context cancels only this wait
cancel(context: Context): Promise<void>; // cancels the job itself, for everyone
}
An IndexService.start(root, context) returning an IndexJob validates the root, creates its own AbortController and a detached telemetry root, and returns the job. The job crosses the wire as a remote object reference (rpc.md) — an opaque ID the client proxy holds. It makes the cancellation domains concrete: wait() abort is invocation cancellation; cancel() is service-owned. The exposure registry must release completed references under an explicit lifetime policy.
The server: directory, management, and routing
The server host does two jobs. It owns server-wide services—listing, creating, deleting, and attaching to sessions—and it routes session traffic between attached presentations and the session workers it manages. Routing is host infrastructure that plugin code does not implement.
A server facet is shared by every session and presentation connected to the server. It should be used only for inherently server-wide features. Per-session feature data belongs in session facets.
Server host context
interface FleetPluginScope {
readonly managed: ManagedSessionsView; // sessions managed by this server
readonly attachments: AttachmentsView; // bind/unbind a client's selected session
}
interface CodingAgentServerPluginContext extends PluginLifecycleScope {
readonly fleet: FleetPluginScope;
// plus the same provide/use/remoteState/remoteEvents as the session host context
}
The raw SessionRepo, storage handles, unrestricted process-kill authority, routing map, and routing machinery stay with the server application:
interface ManagedSessionRecord {
sessionId: string;
title: string;
workspaceId: string;
ownerId: string;
cwd: string; // ownerId and cwd never leave the server
status: "starting" | "active" | "idle" | "closed" | "unreachable";
updatedAt: string;
}
type ManagedSessionChange = { type: "created" | "changed" | "deleted"; record: ManagedSessionRecord };
interface ManagedSessionsView {
snapshot(): ManagedSessionRecord[];
onChanged(listener: (change: ManagedSessionChange, context: Context) => void): () => void;
create(options: { title: string; workspaceId: string }, context: Context): Promise<ManagedSessionRecord>;
remove(sessionId: string, context: Context): Promise<void>;
}
Shared contract
The directory is read; management mutates and selects. Both are presentation-safe: ownerId and cwd are stripped from summaries.
export interface SessionRecordSummary {
sessionId: string;
title: string;
workspaceId: string;
status: ManagedSessionRecord["status"];
updatedAt: string;
}
export type SessionDirectoryEvent =
| { type: "created" | "changed"; session: SessionRecordSummary }
| { type: "deleted"; sessionId: string };
export interface SessionDirectoryService {
readonly state: RemoteState<{ revision: number; sessions: SessionRecordSummary[] }>;
readonly events: RemoteEvents<SessionDirectoryEvent>;
}
export const SessionDirectory = defineRemoteService<SessionDirectoryService>("session-directory", {
state: ["state"],
events: ["events"],
});
export interface SessionManagementService {
create(options: { title: string }, context: Context): Promise<SessionRecordSummary>;
remove(sessionId: string, context: Context): Promise<void>;
attach(sessionId: string, context: Context): Promise<void>;
detach(context: Context): Promise<void>;
}
export const SessionManagement = defineRemoteService<SessionManagementService>("session-management");
Server facet
// server.ts
export function sessionDirectoryServerFacet(pluginContext: CodingAgentServerPluginContext) {
const { managed, attachments } = pluginContext.fleet;
const state = pluginContext.remoteState({ revision: 0, sessions: [] as SessionRecordSummary[] });
const events = pluginContext.remoteEvents<SessionDirectoryEvent>();
function publish(change: ManagedSessionChange, context: Context) {
state.set({ revision: state.value.revision + 1, sessions: managed.snapshot().map(toSummary) }, context);
events.emit(toDirectoryEvent(change), context);
}
pluginContext.own(managed.onChanged(publish));
pluginContext.onActivate(() =>
state.set({ revision: 1, sessions: managed.snapshot().map(toSummary) }, BACKGROUND_CONTEXT),
);
pluginContext.provide(SessionDirectory, { state, events });
pluginContext.provide(SessionManagement, {
async create(options, context) {
const client = requireClientIdentity(context);
return toSummary(await managed.create({ title: options.title, workspaceId: client.workspaceId }, context));
},
async remove(sessionId, context) {
authorizeTarget(requireClientIdentity(context), managed.snapshot(), sessionId);
await managed.remove(sessionId, context);
},
async attach(sessionId, context) {
const client = requireClientIdentity(context);
authorizeTarget(client, managed.snapshot(), sessionId);
await attachments.bind(client.clientId, sessionId, context);
},
async detach(context) {
await attachments.unbind(requireClientIdentity(context).clientId, context);
},
});
}
function authorizeTarget(client: ClientIdentity, records: ManagedSessionRecord[], sessionId: string) {
const record = records.find((candidate) => candidate.sessionId === sessionId);
if (record === undefined || record.workspaceId !== client.workspaceId) {
throw new RemoteServiceError("not_authorized", `Not accessible: ${sessionId}`);
}
}
function toSummary({ sessionId, title, workspaceId, status, updatedAt }: ManagedSessionRecord): SessionRecordSummary {
return { sessionId, title, workspaceId, status, updatedAt };
}
Every call is authorized against the client identity that transport policy installed server-locally, never against identity supplied in ordinary arguments.
TUI facet: the picker
// tui.ts
export async function sessionPickerTuiFacet(pluginContext: CodingAgentTuiPluginContext) {
const directory = await pluginContext.server.use(SessionDirectory);
const management = await pluginContext.server.use(SessionManagement);
pluginContext.commands.register("sessions.switch", async (context) => {
const entries = directory.state.value.sessions;
const picked = await pluginContext.ui.select(
"Sessions",
entries.map((entry) => pickerLabel(entry, pluginContext.session.attachment.value)),
{ signal: context.abortSignal },
);
if (picked === undefined) return;
await management.attach(entries[choiceIndex(entries, picked)].sessionId, context);
});
directory.state.subscribe((next) => renderSessionList(next));
}
The TUI facet consumes a service provided by the one connected server. There is no session facet in this plugin because sessions do not own discovery or attachment.
Attaching and switching
attach(sessionId) selects the session for this presentation connection:
- the server authorizes the client for one of its managed sessions;
- it closes the client's previous session-scoped requests, subscriptions, and references;
- it binds the session namespace to the selected session worker;
- the session worker hydrates the client with a complete fresh snapshot;
session.attachmentbecomesattached.
Session-namespace proxies are stable across switches: session.use(Models) resolved once keeps working against the new session. Frames belonging to closed subscriptions or requests are dropped.
Routed session call
TUI A (selected session S1): rpc.client chat.prompt
server: authorize client for S1; route to session worker S1 with authenticated client identity
S1: rpc.server chat.prompt — fresh local Context, validated JSON args → lane.prompt(...)
response returns S1 → server → TUI A
Aborting the TUI request sends cancellation through the server to S1, aborting the session-side request controller. Trace carriers pass through routing; Context is reconstructed at the service endpoint.
Routing is host infrastructure
The server routes session traffic contract-agnostically. It parses protocol envelopes—frame kind, request ID, service ID, and selected session—but not plugin business payloads. Validation happens at service endpoints, so the server can route a session plugin service without loading that session facet.
The server stamps routed calls with the client identity it authenticated. The session worker keys connection-owned requests by that identity, preventing collisions and cross-client cancellation. No server facet participates in routing or re-provides session services.
Session-owned deferred interactions: the question plugin
Some session-side work must ask users for a decision. The existing examples/extensions/question.ts shows the experience: the model calls a question tool, a user selects an option or types an answer, and the tool returns that answer with a compact rendering.
A question is not a reverse RPC routed to one eligible presentation. It is shared session-owned data. Every connected TUI or web presentation must be able to show it, a presentation connecting later must discover it, and the session must continue to hold it while no users are connected.
The session facet provides one presentation-safe service. Its tool and service implementation share the built-in durable-request binding described below; no second plugin service or plugin-owned waiter protocol is involved.
Shared contracts
const QuestionParamsSchema = Type.Object({
question: Type.String(),
options: Type.Array(
Type.Object({
label: Type.String(),
description: Type.Union([Type.String(), Type.Null()]),
}),
),
});
type QuestionRequest = Static<typeof QuestionParamsSchema>;
const QuestionResponseSchema = Type.Union([
Type.Object({ outcome: Type.Literal("selected"), index: Type.Integer({ minimum: 0 }) }),
Type.Object({ outcome: Type.Literal("custom"), answer: Type.String() }),
Type.Object({ outcome: Type.Literal("cancelled") }),
]);
type QuestionResponse = Static<typeof QuestionResponseSchema>;
interface QuestionDetails {
question: string;
options: string[];
answer: string | null;
wasCustom: boolean;
}
interface PendingQuestion {
id: string;
request: QuestionRequest;
}
type DurableRequestSubmitResult = { outcome: "accepted" } | { outcome: "not_pending" };
interface QuestionsService {
readonly pending: RemoteState<PendingQuestion[]>;
submitAnswer(id: string, response: QuestionResponse, context: Context): Promise<DurableRequestSubmitResult>;
}
const Questions = defineRemoteService<QuestionsService>("questions", { state: ["pending"] });
const QuestionRequests = defineDurableRequests({
id: "questions",
request: QuestionParamsSchema,
response: QuestionResponseSchema,
});
Questions.pending replicates the latest pending questions to every connected presentation. submitAnswer() is an ordinary asynchronous remote method. The RemoteState adapter keeps subscription callbacks local and transports snapshots and updates internally.
The tool-result helper remains session-local:
function questionResult(request: QuestionRequest, answer: string | null, wasCustom: boolean, text: string) {
return {
content: [{ type: "text", text }],
details: { question: request.question, options: request.options.map((o) => o.label), answer, wasCustom },
} satisfies AgentToolResult<QuestionDetails>;
}
Built-in durable requests
A replay-safe tool waiting for external input is common enough that plugins should not implement memo keys, waiter races, restoration, state projection, or cleanup themselves. defineDurableRequests() declares one typed request/response channel. bindings.durableRequests() binds that declaration to the session Harness and returns:
interface DurableRequests<Request extends JsonValue, Response extends JsonValue> {
readonly pending: RemoteState<Array<{ id: string; request: Request }>>;
wait(
invocation: AgentHarnessToolInvocation,
request: Request,
context: Context,
): Promise<Response>;
submit(id: string, response: Response, context: Context): Promise<DurableRequestSubmitResult>;
}
This is session-side infrastructure, not a fourth remote primitive. A presentation still sees only remote state and the submitAnswer() method deliberately exposed by the plugin.
The helper decomposes into a small process-local join layer over a privileged Harness invocation-request store. createDeferred() and awaitAbortable() below are ordinary shared promise/cancellation utilities:
type RegisterResult<Response> =
| { status: "pending" }
| { status: "resolved"; response: Response };
interface InvocationRequestStore<Request extends JsonValue, Response extends JsonValue> {
readonly pending: RemoteState<Array<{ id: string; request: Request }>>;
register(
invocation: AgentHarnessToolInvocation,
request: Request,
context: Context,
): Promise<RegisterResult<Response>>;
submit(id: string, response: Response, context: Context): Promise<DurableRequestSubmitResult>;
}
function createDurableRequests<Request extends JsonValue, Response extends JsonValue>(
store: InvocationRequestStore<Request, Response>,
) {
const waiters = new Map<string, Deferred<Response>>();
return {
pending: store.pending,
async wait(invocation: AgentHarnessToolInvocation, request: Request, context: Context): Promise<Response> {
const id = invocation.invocationId;
if (waiters.has(id)) throw new Error(`Invocation ${id} is already waiting`);
// Install the local waiter before publishing durable pending state. If a
// subscriber answers immediately after register(), submit() can wake it.
const waiter = createDeferred<Response>();
waiters.set(id, waiter);
try {
const result = await store.register(invocation, request, context);
if (result.status === "resolved") return result.response;
return await awaitAbortable(waiter.promise, context.abortSignal);
} finally {
if (waiters.get(id) === waiter) waiters.delete(id);
}
},
async submit(id: string, response: Response, context: Context): Promise<DurableRequestSubmitResult> {
const result = await store.submit(id, response, context);
if (result.outcome === "accepted") waiters.get(id)?.resolve(response);
return result;
},
};
}
The session binding itself is only composition. DurableRequestDefinition is the schema-bearing token returned by defineDurableRequests(); HarnessInvocationRequests is private host/Harness infrastructure:
async function bindDurableRequests<Request extends JsonValue, Response extends JsonValue>(
definition: DurableRequestDefinition<Request, Response>,
invocationRequests: HarnessInvocationRequests,
): Promise<DurableRequests<Request, Response>> {
const store = await invocationRequests.open(definition);
return createDurableRequests(store);
}
bindings.durableRequests(QuestionRequests) uses this path to open the corresponding InvocationRequestStore and hydrate it before the facet is exposed. The store owns the durable part. Its two operations run on the invocation's lane mutation line:
register(invocation, request):
verify invocation is the current effect_pending, replay-safe tool call
validate request against the channel schema
read the channel's invocation-scoped request and response values
response exists → return resolved(response)
same request exists → return pending
neither exists → commit request; publish pending; return pending
submit(invocationId, response):
locate the open invocation and verify the same effect_pending call still owns it
validate response against the channel schema
request absent → return not_pending
response exists → return not_pending
otherwise → commit response; remove pending; return accepted
The request and response use Harness-owned invocation-memo storage under keys derived from the plugin and channel IDs. Raw memo writes are not exposed to clients or plugins through submit(). The store fences every transition against the current tool call, and the lane mutation line makes the first response win.
On worker replacement, the Harness already restores open operations and their effect-pending tool calls. Opening a registered channel reads its exact request and response memo keys for those calls and rebuilds pending before clients hydrate. submit() can therefore durably answer a restored question even before execute() is replayed and has installed a new local waiter. When the application resumes the operation, safe replay calls wait() with the same invocation ID: register() returns the stored response immediately or joins the still-pending request.
The normal Harness outcome boundary provides cleanup. Once execute() returns, staging the tool result as outcome_ready atomically deletes all invocation memos, including the channel request and response. Cancellation and unsafe external finalization use the same invocation cleanup and remove any pending projection. No plugin-owned question log or settlement hook is required.
Session facet: await one durable request
// session.ts
export async function questionSessionFacet(bindings: SessionPluginBindings) {
const requests = await bindings.durableRequests(QuestionRequests);
bindings.provide(Questions, {
pending: requests.pending,
submitAnswer(id, response, context) {
return requests.submit(id, response, context);
},
});
bindings.tools.add((draft) => {
draft.set("question", {
label: "Question",
description: "Ask users a question and wait for an answer.",
executionMode: "sequential",
replay: "safe",
parameters: QuestionParamsSchema,
async execute(_toolCallId, params, _onUpdate, _toolContext, invocation, context) {
if (params.options.length === 0) return questionResult(params, null, false, "No options provided");
const response = await requests.wait(invocation, params, context);
if (response.outcome === "cancelled") return questionResult(params, null, false, "User cancelled the question");
if (response.outcome === "custom") return questionResult(params, response.answer, true, `User wrote: ${response.answer}`);
const selected = params.options[response.index];
if (selected === undefined) throw new Error("Question response selected an invalid option");
return questionResult(params, selected.label, false, `User selected: ${response.index + 1}. ${selected.label}`);
},
});
});
}
replay: "safe" is the durable suspension contract. While the worker is alive, wait() leaves execute() pending on a local promise. If the worker dies, that promise disappears but the Harness retains the effect-pending call and the channel retains its request or response. Safe replay re-enters execute() and rejoins the same durable request. With no answer, it may remain there indefinitely.
While the worker is live, all clients resolve Questions to this same session facet. They see the same pending projection and may race to call submitAnswer(), but only the first durable response commit is accepted. The authority and arbitration stay in the session facet rather than in the server or any one presentation.
TUI and web facets: observe, answer, and render
// tui.ts
export function questionTuiFacet(bindings: TuiPluginBindings) {
const questions = bindings.use(Questions);
bindings.own(
questions.pending.subscribe((pending, context) => {
void reconcileQuestionDialogs(bindings.ui, pending, (id, response, answerContext) =>
questions.submitAnswer(id, response, answerContext),
).catch((error) => reportQuestionUiError(error, context));
}),
);
bindings.toolRenderers.add<QuestionDetails>("question", questionRenderer);
}
Each presentation independently subscribes to the same session state. If TUI and web are both connected, both open the question. When either answers, the state update makes both close it. A late or reconnected presentation hydrates the current pending state automatically. With no connected presentation, there are no remote subscribers, but the authoritative pending question remains session-owned.
A web facet uses the same Questions binding with a browser dialog. A headless client may ignore the service. Similar features—permissions, OAuth, or editor requests—should first decide whether they are shared deferred session state or ordinary calls; they do not get a separate interaction framework. Secrets need explicit contracts and must never enter logs or telemetry attributes.
Lifecycle and disposal
Every facet-owned resource — service registrations, contributions, state subscriptions, watchers, timers, in-flight RPCs, subprocesses, overlays — is owned by the facet's kernel scope and disposed when that scope closes, in reverse manifest order. Scoped capabilities enforce this automatically for hooks and event subscriptions; onDispose handles the rest. Removing a plugin disposes its scope in every host that loaded a facet and rebuilds any contribution registries it touched; neither requires the plugin to undo anything by hand.
Connection loss, errors, and security
Disconnect behavior, from the plugin author's perspective:
- A presentation disconnects. Its server aborts the client's active requests, closes its session-routed resources, and the selected session's
onClientDetachfires. Session-owned work continues per application policy. A pending question remains session-owned; its local replica becomes stale and any in-flightsubmitAnswer()invocation fails. - A session worker disconnects or crashes. Its server fails routed in-flight calls with
session_unavailableand updates the managed record's status. Attached presentations seeattachment.status === "degraded"while the server connection stays healthy, so the picker still works and the user can attach elsewhere. - A process loses its server connection. A presentation loses both namespaces. A session worker loses server services and all attached presentations at once; unattended-session policy decides whether it exits.
- Reconnect and reattach always hydrate from a fresh authoritative snapshot; prior remote references are invalid unless the exposure has explicitly session-stable identity. Never blindly replay a mutation after an uncertain disconnect — a replayed
select()is harmless, a replayedprompt()is not. Reconnect, hydrate, and reconcile, or design the operation around a stable operation ID with explicit lookup semantics.
Errors cross the wire as a JSON envelope { code, message, data? } with stable codes. Expected service errors use stable codes or result values; unexpected exceptions become an internal error with safe metadata — no stacks or sensitive causes by default. Cancellation, disconnect, unknown service/method, invalid arguments/results, stale references, not_attached, not_authorized, unknown_session, and session_unavailable need distinct codes.
Security rules every providing host (session and server alike) must enforce:
- remote service IDs and members are allowlisted by trusted manifests or exposure descriptors; local services are never discoverable remotely;
- business arguments, results, state, and events are validated as JSON; protocol envelopes cannot be forged as ordinary values;
- clients cannot choose context position, server typed values, telemetry parents, or cancellation targets other than their own request IDs;
- credentials, prompts, completions, tool arguments/results, and filesystem contents are not exposed unless an explicit contract permits them; state snapshots contain only client-safe data;
- remote methods authorize server-side even when the TypeScript client surface hides them.
The coding agent as a plugin manifest
The coding agent is one manifest of built-in and third-party plugins; each app host loads its facets through the same kernel in deterministic order. Server facets cover the directory/management services, authentication and client authorization, and worker spawn/stop policy and health. Session facets cover session creation/restoration and the scoped Harness facade; providers, model selection, and authentication; tools, wrappers, and permissions; prompt/steer/abort/compaction services; transcript persistence and event projection; filesystem and subprocess effects; deferred interaction authority; unattended-session policy; and server service consumption where a feature needs server-wide data. TUI facets cover the chat screen, transcript rendering, editor, commands, keybindings, pickers, renderers, screens/slots/dialogs, and themes; a web host carries analogous browser facets. Shared contracts are service tokens with JSON-safe DTOs, latest-value state and semantic event types, presentation-local screen/slot tokens, stable renderer discriminators, and portable structured errors.
The generic kernel knows none of these domain concepts; each app host knows only its own.
Open decisions
Before this becomes normative:
- the exact minimal kernel contract (scope shape, phase ordering, failure policy), the built-in manifest, and the concrete server/session/TUI host context surfaces;
- the logical-manifest format, per-host entry-point resolution, and cross-process version pinning;
- whether directory state is projected per client (workspace-scoped snapshots) or one presentation-safe value plus method authorization;
- multiple selected sessions per presentation connection (a multi-pane web UI) — deferred; it changes the session-namespace API;
- authentication of presentations and session workers, and protocol version negotiation;
- the exact
RemoteService/exposure-descriptor API, and the context-position and JSON-safe optional-argument policy fromrpc.md; - whether
RemoteStateis generic RPC infrastructure or host infrastructure; snapshot granularity; exact hydration/delivery-context semantics; - state/event flow control and per-client buffering at the server; reference lifetime and garbage collection;
- the stable error envelope and expected-error registration; activation/disposal ordering, optional dependencies, and shared-proxy lifetime;
- the exact
DurableRequestsAPI, invocation-memo key ownership and restored-channel hydration; pending-question cancellation policy, remote-state flow control, and answer authorization; - package boundaries between the generic kernel, agent plugin contracts, generic protocol machinery, and coding-agent host integration.
Testing strategy
The handoff should include a reusable two-transport test matrix (loopback plus a real framed transport) covering:
- Composition: hosts start from one plugin manifest, not hard-coded features; per-host entry-point resolution with no session modules reachable in a presentation bundle; provide/demand-resolve round trip; shared proxy/replica across concurrent consumers; local services unreachable remotely; duplicate/missing service failures; activation only after registration; reverse-order disposal.
- Connections:
Connectperforms one abortable attempt and the host owns retries; peer identity comes from the accepting server's handshake; session and presentation hosts connect to that server, andserver.localruns the same host boundaries without sockets. - RPC and context: JSON call and
voidresult; invalid argument/result and unknown service/member rejection; client span →rpc.client→rpc.server→ service span; per-call cancellation isolation; disconnect aborts active calls; no callback, context, signal, telemetry object, or secret in wire JSON. - State and events: snapshot plus concurrent update with no gap; update ordering and detached values; reconnect replaces stale state; subscribe/unsubscribe and disconnect cleanup; deliveries carry reconstructed source contexts; immediate snapshot callbacks run under the hydration context.
- Registries: ordered provider contributions rebuild deterministically; tool wrappers compose once and rebuild correctly after removal.
- Routing: attach authorizes at the server and rejects cross-workspace targets; attach/switch closes previous routed requests and hydrates the selected session; a routed call reconstructs
Contextat the session worker, with cancellation and trace carriers traversing the server; per-client keying prevents ID collisions; the server routes services whose contracts it does not load; session-worker failure leaves server services healthy and updates directory status; presentation disconnect cleanup reaches the session; summaries contain noownerIdorcwd. - Boundaries: scoped agent and fleet capabilities cannot reach host ownership or whole-registry mutation; raw Harness/Session/SessionRepo capabilities unreachable from any client connection; job
waitcancellation distinct fromjob.cancel(); stale/closed reference rejection; one pending question appears through remote state in simultaneous TUI and web clients, survives having no connected presentation, hydrates from its invocation memo after worker restart before tool replay, accepts an answer with or without a live waiter, returns that answer when the Harness safely replays the tool, rejects later answers, cleans up with durable tool-result staging, and closes in every presentation; invocation cancellation writes no durable cancellation state.